0

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..

4
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by JamesCherrill
0

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!

Edited by majestic0110: added instruction

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

}
0

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
  ...
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.