Hi, i am new here and i want an help in add the actionListener to the component of JCombo Box. Like there is Combo Box in Which there are components like name of color. When i click any component, for example i click Green color the background turns into Green. Thanx in advance..

Recommended Answers

All 5 Replies

Can you post the code you are having trouble with?

Here is the listener, all you need to do further is get the selected value of the combo (within the actionPerformed(ActionEvent e) method )and then change the colour of the background based on that value!

myCombobox.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        //change back ground colour
    }
});

Hope that helps!

public class Backgroundcolor implements ActionListener
{
    private JComboBox change;
    public Backgroundcolor()
    {
        JFrame f = new JFrame();
        JPanel panel = new JPanel();
        panel.setBackground(Color.DARK_GRAY);
        f.setSize(500,600);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[] Change = {"Green","Blue"};
        change = new JComboBox(Change);
        change.setSize(120,30);
        change.setLocation(300,250);
        change.addActionListener(this);
        panel.add(change);
        f.setResizable(false);
        f.setVisible(true);
        f.add(panel);

    }
    public static void main (String[] args) 
        {
            new Backgroundcolor();
          }
               public void actionPerformed(ActionEvent e)
               {
                if(e.getSource()==change.getSelectedIndex())
                 {
                    change.setBackground(Color.blue);
                 }
               }

}

This is my whole code, so please help me according to that...

if(e.getSource()==change.getSelectedIndex())

e.getSource() is the object where the event happened
change.getSelectedIndex() is the line that's currently selected
these are two quite different things, and will never be equal.

You probabaly want something more like:

if(e.getSource()==change) {  // use clicked in the change object
  int selectedLine = change.getSelectedIndex();  // this is the number of the selected line
  // change background colour
  ...
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.