Swing Examples - Using Comboboxes
Following example showcases how to use standard comboboxes in a Java Swing application.
We are using the following APIs.
JComboBox − To create a standard combobox.
JCheckBox.setSelectedIndex(index); − To select an item.
JCheckBox.getSelectedItem(); − To get a selected item.
Example - Using Comboboxes in Swing Application
SwingTester.java
package com.tutorialspoint;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(492, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
String[] numbers = {"One", "Two", "Three", "Four", "Five"};
JComboBox<String> comboBox = new JComboBox<>(numbers);
comboBox.setSelectedIndex(3);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox)e.getSource();
JOptionPane.showMessageDialog(frame,combo.getSelectedItem());
}
});
panel.add(comboBox);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
Output
Compile and Run the program and verify the output −
swingexamples_comboboxes.htm
Advertisements