2013-12-14 50 views
0

突出当JComboBox刚刚制成,并将所选择的项目的所有的背景只是正常和白色:
(忽略文本后的巨大间距)删除的JComboBox

before

当然后我打开列表并将光标悬停在某个项目上,该项目突出显示,全部正常,没有任何问题。

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

after

所以我的问题是:
我怎样才能使高亮消失?
最好不要与来自社区的软件包或超载或其他任何困难。

如果我是正确的,它必须在组合框的动作监听器的'根'?
所以:

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

您可能只想尝试不同的[外观和感觉](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html)。 – jaco0646

+1

*“我怎样才能使突出显示消失?”*我(作为假设用户)如何知道何时该组合。有重点?这听起来像是另一个“无法使用的GUI”。 :( –

+0

@AndrewThompson不,不,我只想要突出显示一旦选择了该项目,而不是当你被选中时(所以当在下拉菜单中悬停在项目上时) –

回答

0

为了类似的问题使人们更容易,这里是我写的渲染代码:

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; 
    } 
} 

编辑:上面的代码似乎并没有为正确,代码更新工作,应该工作现在一切都好了

3

高亮显示是通过组合框的默认渲染完成。

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

+0

这个解决方案真的很有帮助,一开始看起来真的很复杂(我是一个真正的新手),但最终似乎很容易 –