Syntax error How to handle action event for JComboBox in Java?

How to handle action event for JComboBox in Java?



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:

Updated on: 2019-07-30T22:30:25+05:30

829 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements