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

Dani AI

Generated

Short answer: the listener approach is right, but the original code mixes up types and updates the wrong component. gave the correct place to add an ActionListener and correctly pointed out that comparing e.getSource() to change.getSelectedIndex() will never work. The fixes are: compare the source to the combo box (or read the selected item), change the panel background (not the combo box), build the UI on the Event Dispatch Thread, and add components before making the frame visible.

Key problems in the posted code

  • e.getSource() returns an Object (the combo box). change.getSelectedIndex() returns an int. They are different types and should not be compared.
  • Calling change.setBackground(...) only colors the JComboBox. You want panel.setBackground(...).
  • The JPanel should be accessible to the listener (make it a field), and f.add(panel) should happen before f.setVisible(true).
  • Build the GUI on the EDT (use SwingUtilities.invokeLater).

A compact, robust fix (keeps things local and safe):

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class BackgroundColor {
    private final JPanel panel = new JPanel();

    public BackgroundColor() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JFrame("Color picker");
                panel.setBackground(Color.DARK_GRAY);

                final JComboBox<String> change = new JComboBox<String>(new String[]{"Green","Blue"});
                change.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        String sel = (String) change.getSelectedItem();
                        if ("Green".equalsIgnoreCase(sel)) panel.setBackground(Color.GREEN);
                        else if ("Blue".equalsIgnoreCase(sel)) panel.setBackground(Color.BLUE);
                    }
                });

                panel.add(change);
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(panel);
                f.pack();
                f.setLocationRelativeTo(null);
                f.setResizable(false);
                f.setVisible(true);
            }
        });
    }

    public static void main(String[] args) {
        new BackgroundColor();
    }
}

Extra tips: prefer getSelectedItem() or getSelectedIndex() (and compare integers) over type-mismatched checks; use equalsIgnoreCase for user-facing strings; and avoid manual setSize/setLocation—use layout managers and pack() for predictable layout.

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.