How to handle action event for JComboBox in Java?

Java 8Object Oriented ProgrammingProgramming

The following is an example to handle action event for JComboBox in Java:

Example

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JComboBox<String> combo = new JComboBox<>(new String[] { "One","Two", "Three","Four","Five", "Six" });
      JButton add = new JButton("Add");
      add.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            combo.addItem("New");
         }
      });
      frame.add(combo);
      frame.add(add, BorderLayout.NORTH);
      frame.setSize(500, 100);
      frame.setVisible(true);
   }
}

Output

Now, we have the following items:

Now, click “Add” above to add a new item on runtime. After clicking, a new item would be visible in the bottom as shown in the following screenshot:

raja
Published on 02-May-2019 10:59:20
Advertisements