Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign different colors to items in JComboBox?

Tags:

java

swing

I have a JComboBox and have 10 string items added in it. I want to assign different colors to each item. How i can achive this? Please help.

like image 332
Mandar Avatar asked Dec 11 '25 00:12

Mandar


2 Answers

The example in Chandru's answer looks like a lot of code so I can understand why you're asking for an easier solution. However, if you subclass DefaultListCellRenderer a lot of the work is done for you, as this renderer is a subclass of JLabel.

JList list = ... // Create JList

// Install custom renderer.
list.setCellRenderer(new DefaultListCellRenderer() {
  public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

    // Request superclass to render the JLabel.
    Component ret = super.getListCellRenderer(list, value, index, isSelected, cellHasFocus);

    // Now conditionally override background if cell isn't selected.
    if (!isSelected) {
      String s = String.valueOf(value);

      if (s.equals("Foo")) {
        ret.setBackground(Color.RED);
      } else {
        ret.setBackground(Color.GREEN);
      }
    }

    return ret;
  }
});
like image 103
Adamski Avatar answered Dec 13 '25 14:12

Adamski


You must use a custom list cell renderer. Look into this how-to for an example.

like image 25
Chandra Sekar Avatar answered Dec 13 '25 13:12

Chandra Sekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!