永久更改JComboBox所选项目的颜色

时间:2012-12-02 17:15:07

标签: java swing user-interface jcombobox

请查看以下代码

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

public class JCombo extends JFrame
{
    JComboBox com1;

    public JCombo()
    {


        com1 = new JComboBox();

        com1.addItem("Select");
        com1.addItem("One");
        com1.addItem("two");
        com1.addItem("Three");

        com1.addItemListener(new Com1Action());

        this.setLayout(new FlowLayout());
        this.add(com1);

        this.pack();
        this.validate();
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private class Com1Action implements ItemListener
    {
        public void itemStateChanged(ItemEvent ae)
        {
            if(ae.getStateChange() == ItemEvent.SELECTED)
            {
                com1.getSelectedItem();
            }
        }
    }

    public static void main(String[]args)
    {
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            new JCombo();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

在这里,我想在选择项目时为所选项目应用颜色。我怎样才能做到这一点?

例如:

User selects "One" - Now "One" changes to blue
  User selects "Two" - Now "Two" changes to blue. "One" is also blue as well, because we changed the colour at the first place
    User selected "Three" - Now "Three" changes to blue. "One" and "Two" remains blue as well

更新

我用自定义渲染器对其进行了编码。现在它突出显示所选项目,但只要鼠标移动,颜色就会恢复到原始状态。换句话说,这里唯一发生的事情是更改高亮颜色,而不是将颜色应用于所选项永久

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

public class JCombo extends JFrame
{
    JComboBox com1;

    public JCombo()
    {


        com1 = new JComboBox();
        com1.setLightWeightPopupEnabled(true);

        com1.addItem("One");
        com1.addItem("two");
        com1.addItem("Three");

        com1.setRenderer(new MyCellRenderer());

        com1.addItemListener(new Com1Action());

        this.setLayout(new FlowLayout());
        this.add(com1);

        this.pack();
        this.validate();
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private class Com1Action implements ItemListener
    {
        public void itemStateChanged(ItemEvent ae)
        {
            if(ae.getStateChange() == ItemEvent.SELECTED)
            {
                com1.getSelectedItem();

            }
        }
    }

   class MyCellRenderer extends JLabel implements ListCellRenderer<Object> 
   {
     public MyCellRenderer() 
     {
         setOpaque(true);
     }

     public Component getListCellRendererComponent(JList<?> list,
                                                   Object value,
                                                   int index,
                                                   boolean isSelected,
                                                   boolean cellHasFocus) {

         setText(value.toString());

         Color background = Color.white;
         Color foreground = Color.black;

         // check if this cell represents the current DnD drop location
         JList.DropLocation dropLocation = list.getDropLocation();

         if (dropLocation != null
                 && !dropLocation.isInsert()
                 && dropLocation.getIndex() == index) {



         // check if this cell is selected
         } else if (isSelected) {
             background = Color.RED;
             foreground = Color.WHITE;

         // unselected, and not the DnD drop location
         } else {
         };

         setBackground(background);
         setForeground(foreground);

         return this;
     }
 }


    public static void main(String[]args)
    {
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            new JCombo();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

4 个答案:

答案 0 :(得分:4)

这需要Providing a Custom Renderer; API包含example

附录:唯一发生的事情是更改高亮颜色,而不是将颜色应用于所选项永久

永久地改变某些东西意味着有一个存储该信息的地方。我看到两个选择:

  • 在您选择的state中添加ComboBoxModel字段,并使用它来调整渲染器中的背景颜色。您可以使用list.getModel()

  • 访问渲染器内的模型
  • 切换到JListJTable并使用允许多项选择的ListSelectionModel,如@mKorbel建议的here

答案 1 :(得分:1)

如果您只想更改selecteditem的前景颜色,请使用下面的代码

combobox.getEditor()getEditorComponent()setForeground(Color.GREEN);

如果你想改变包括选择项在内的所有项目的前景色,那么也可以使用上面的代码以及代码。

   combobox.setRenderer(new DefaultListCellRenderer() {
@Override
public void paint(Graphics g) {
    setBackground(Color.WHITE);
    setForeground(Color.GREEN);
    super.paint(g);
}

});

答案 2 :(得分:0)

您是否尝试过.setBackground(Color c)方法?

Java的优点在于它的文档非常全面。

请在此处查看JComponent的文档:JComponent Docs

答案 3 :(得分:0)

主要有两种方式

  • 1)更改UIManager格式JCombobox或
  • 中的键值
  • 2)覆盖DefaultListCellRenderer,如果是isSelected

    UIManager.put("ComboBox.background", new ColorUIResource(Color.yellow));
    UIManager.put("ComboBox.selectionBackground", new ColorUIResource(Color.magenta));
    UIManager.put("ComboBox.selectionForeground", new ColorUIResource(Color.blue));