Java jcombobox basic tutorial and examples
I can give you a basic tutorial and examples for using JComboBox in Java.
JComboBox is a class in the Java Swing package that provides a drop-down list component. You can create a JComboBox and add it to a JFrame or other container to allow the user to select one item from a list of options.
Here's an example of creating a simple JComboBox:
import javax.swing.JComboBox; import javax.swing.JFrame; public class MyComboBox extends JFrame { public MyComboBox() { super("Combo Box Example"); String[] options = {"Option 1", "Option 2", "Option 3"}; JComboBox<String> comboBox = new JComboBox<>(options); add(comboBox); pack(); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new MyComboBox(); } }
In this example, we create a new JFrame and add a JComboBox to it with the options "Option 1", "Option 2", and "Option 3". We then call the pack()
method to resize the JFrame to fit its contents, make it visible with setVisible(true)
, and set the default close operation to exit the application when the JFrame is closed.
When you run this program, it will display a window with a drop-down list containing the options "Option 1", "Option 2", and "Option 3".
Here's an example of reading the selected item from the JComboBox:
import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JOptionPane; public class MyComboBox extends JFrame { public MyComboBox() { super("Combo Box Example"); String[] options = {"Option 1", "Option 2", "Option 3"}; JComboBox<String> comboBox = new JComboBox<>(options); comboBox.addActionListener(e -> { String selectedOption = (String) comboBox.getSelectedItem(); JOptionPane.showMessageDialog(null, "Selected option: " + selectedOption); }); add(comboBox); pack(); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new MyComboBox(); } }
In this example, we add an ActionListener to the JComboBox using a lambda expression. The ActionListener reads the selected item from the JComboBox using getSelectedItem()
and displays a message dialog indicating the selected option.
Now, when you run the program and select an option from the drop-down list, it will display a message dialog with the selected option.
I hope this helps you get started with using JComboBox in Java!