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

Java 永久更改JComboBox所选项目的颜色,java,swing,user-interface,jcombobox,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("

请看一下下面的代码

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

    }
}
在这里,我想在选中某个项目时为该项目应用颜色。我该怎么做

例:

更新

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

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

    }
}
导入java.awt.event.*;
导入javax.swing.*;
导入java.awt.*;
公共类JCombo扩展了JFrame
{
jComboxCom1;
公共JCombo()
{
com1=新的JComboBox();
com1.setLightWeightPopupEnabled(真);
com1.补充项目(“一”);
com1.补充项目(“两个”);
com1.补充项目(“三”);
com1.setRenderer(新的MyCellRenderer());
com1.addItemListener(新的Com1Action());
this.setLayout(新的FlowLayout());
本条增补(com1);
这个包();
这个。validate();
此.setVisible(true);
此.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
私有类Com1Action实现ItemListener
{
公共无效itemStateChanged(ItemEvent ae)
{
如果(ae.getStateChange()==ItemEvent.SELECTED)
{
com1.getSelectedItem();
}
}
}
类MyCellRenderer扩展了JLabel实现ListCellRenderer
{
公共菌丝体()
{
set不透明(true);
}
公共组件GetListCellRenderComponent(JList列表,
对象值,
整数索引,
他当选了,,
布尔单元(聚焦){
setText(value.toString());
颜色背景=Color.white;
前景色=Color.black;
//检查此单元格是否表示当前DnD放置位置
JList.DropLocation-DropLocation=list.getDropLocation();
if(dropLocation!=null
&&!dropLocation.isInsert()
&&dropLocation.getIndex()=索引){
//检查是否选中此单元格
}否则,如果(当选){
背景=颜色。红色;
前景=颜色。白色;
//未选择,而不是DnD放置位置
}否则{
};
挫折背景(背景);
设置前景(前景);
归还这个;
}
}
公共静态void main(字符串[]args)
{
尝试
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
新JCombo();
}
捕获(例外e)
{
e、 printStackTrace();
}
}
}

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

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

参见此处JComponent的文档:

这需要;该API包括一个

附录:唯一发生的事情是更改突出显示颜色,而不是将颜色永久地应用于所选项目

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

  • 状态
    字段添加到所选的
    ComboBoxModel
    中,并使用它来调节渲染器中的背景色。您可以使用
    list.getModel()
    访问渲染器内的模型

  • 切换到
    JList
    JTable
    ,并使用@mKorbel建议的允许多选的
    ListSelectionModel


    • 主要有两种方式

      • 1) 更改UIManager表单JCombobox中的键值或
      • 2) 如果选择,则覆盖DefaultListCellRenderer

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

      如果只想更改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);
      }
      

      }))

      @bwheeler96:该方法不能用于为特定项目设置颜色。对于您的更新,JLabel的默认颜色是透明的。高亮显示所选项目时,需要确保调用setOpaque(true)。通常我会使用set不透明(isSelected)之类的东西
         combobox.setRenderer(new DefaultListCellRenderer() {
      @Override
      public void paint(Graphics g) {
          setBackground(Color.WHITE);
          setForeground(Color.GREEN);
          super.paint(g);
      }