PeakGen
PeakGen

Reputation: 23025

Changing the colour of JComboBox selected item permanantly

Please have a look at the following code

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

    }
}

In here, I want to apply a colour to the selected item, when an item is selected. How can I do that?

ex:

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

UPDATE

I re coded this with a custom renderer. Now it is highlight the selected item, but as soon as the mouse moves, the colours comes back to the original state. In other words, the only thing happened here is changing the highlight color, not applying a colour to the selected item permanently

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

    }
}

Upvotes: 2

Views: 9734

Answers (4)

Venkatesh Bandarapu
Venkatesh Bandarapu

Reputation: 401

if you want change only foreground color of selecteditem then use below code

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

if you want to change the foreground color of all items including seleted item then use above code as well below code also.

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

});

Upvotes: 2

Deepak Odedara
Deepak Odedara

Reputation: 491

there are two ways mainly

  • 1)change keys value in UIManager form JCombobox or
  • 2)override the DefaultListCellRenderer, if 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));
    

Upvotes: 1

trashgod
trashgod

Reputation: 205785

This requires Providing a Custom Renderer; the API includes an example.

Addendum: the only thing happening is changing the highlight color, not applying a colour to the selected item permanently.

Changing something permanently implies having a place to store that information. I see two choices:

  • Add a state field to your chosen ComboBoxModel and use it to condition the background color in the renderer. You can access the model inside the renderer using list.getModel().

  • Switch to JList or JTable and use a ListSelectionModel that allows multiple selections, as suggested here by @mKorbel.

Upvotes: 4

OneChillDude
OneChillDude

Reputation: 8006

Have you tried the .setBackground(Color c) method?

The nice thing about Java is that it is extremely thorough in its documentation.

See the docs for the JComponent here: JComponent Docs

Upvotes: 0

Related Questions