Swing – Call a Method when Dropdown Item Selected
In this example, We will show you simple Java program about, How to call a method when dropdown item selected in Swing. This example program has been tested and shared with output.
Sample Program
package com.dineshkrish; import java.awt.BorderLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; /** * * @author Dinesh Krishnan * */ public class DropdownExample extends JFrame { private JComboBox<String> comboBox; private JLabel label; public DropdownExample(String title) { // setting JFrame properties super.setTitle(title); super.setDefaultCloseOperation(EXIT_ON_CLOSE); super.setSize(500, 250); super.setVisible(true); super.setLayout(new BorderLayout()); init(); } private void init() { comboBox = new JComboBox<String>(); // setting the items to combo-box comboBox.addItem("One"); comboBox.addItem("Two"); comboBox.addItem("Three"); comboBox.addItem("Four"); comboBox.addItem("Five"); comboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { // calling a method when Item changed in the drop-down doSomething((String) event.getItem()); } }); label = new JLabel(); this.add(comboBox, BorderLayout.NORTH); this.add(label, BorderLayout.SOUTH); } private void doSomething(String selectedValue) { // changing the label value label.setText("You have selected : " + selectedValue); } public static void main(String[] args) { new DropdownExample("Dropdown Example - Calling method when item selected..."); } }
Output
References
How to Create a Dropdown using Java
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet