【问题标题】:Delete highlighting in JComboBox删除 JComboBox 中的突出显示
【发布时间】:2014-01-02 12:05:55
【问题描述】:

JComboBox 刚刚创建并添加并且所选项目的所有背景都是正常的白色时:
(忽略正文后的巨大间距)

当我打开列表并将光标悬停在一个项目上时,该项目会突出显示,一切正常,没有任何问题。

但现在的问题是,一旦我点击了一个项目,突出显示就会保持:

所以我的问题是:
如何使突出显示消失?
最好不要对来自社区的软件包或超载或其他任何事情造成困难。

如果我是对的,它必须位于组合框的动作侦听器的“根”中?
所以:

public void actionPerformed(ActionEvent e)
{
    if(e.getSource() == comboBox)
    {
        // code to delete the highlighting
    }
}

【问题讨论】:

  • 您可能只想尝试不同的Look and Feel
  • “我怎样才能使突出显示消失?” 我(作为假设的用户)如何知道该组合何时出现。有重点吗?这听起来像是另一个“无法使用的 GUI”。 :(
  • @AndrewThompson 不,不,我只希望在选择项目后高亮显示消失,而不是在您被选择时(因此当将鼠标悬停在下拉菜单中的项目上时)
  • “所以当鼠标悬停在下拉菜单中的项目上时” 那么当在 GUI 上切换时它不应该显示?这就是我所警告的......
  • “我个人的看法是,重点部分没有那么漂亮。” 所以给自己力量,听听@jaco0646 的明智建议!我敢打赌你的老师会更喜欢看这个应用程序。在 Native PLAF 中,而不是试图处理你似乎正在创造的这种可憎的东西。

标签: java swing jcombobox highlight


【解决方案1】:

突出显示由组合框的默认渲染器完成。

请参阅 Providing Custom Renderers 上的 Swing 教程部分,了解提供您自己的自定义渲染器的示例。您只需要一个不会根据所选值更改背景/前景的渲染器。

【讨论】:

  • 这个解决方案真的很有帮助,一开始看起来很复杂(我是一个真正的菜鸟),但最后似乎很容易
【解决方案2】:

为了方便有类似问题的人,这里是我写的渲染器代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ComboBoxRenderer extends JLabel implements ListCellRenderer
{
    private boolean colorSet;
    private Color selectionBackgroundColor;

    public ComboBoxRenderer()
    {
        setOpaque(true);
        setHorizontalAlignment(LEFT);
        setVerticalAlignment(CENTER);
        colorSet = false;
        selectionBackgroundColor = Color.red; // Have to set a color, else a compiler error will occur
    }

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
    {
        // Check if color is set (only runs the first time)
        if(!colorSet)
        {
            // Set the list' background color to original selection background of the list
            selectionBackgroundColor = list.getSelectionBackground();
            // Do this only one time since the color will change later
            colorSet = true;
        }

        // Set the list' background color to white (white will show once selection is made)
        list.setSelectionBackground(Color.white);

        // Check which item is selected
        if(isSelected)
        {
            // Set background color of the item your cursor is hovering over to the original background color
            setBackground(selectionBackgroundColor);
        }
        else
        {
            // Set background color of all other items to white
            setBackground(Color.white);
        }

        // Do nothing about the text and font to be displayed
        setText((String)value);
        setFont(list.getFont());

        return this;
    }
}

编辑:以前的代码似乎不能正常工作,代码已更新,现在应该可以正常工作了

【讨论】:

    猜你喜欢
    • 2011-08-31
    • 2021-01-22
    • 2020-11-12
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    相关资源
    最近更新 更多