JComboBox
in Java is a part of the Swing library and is used to create a dropdown list that allows the user to select an item from a predefined set of options. It combines the functionality of a combo box (a drop-down list) with the ability to select items either by clicking on the list or typing in the input field.
Here are key features of JComboBox
:
- Dropdown List: It displays a list of items for the user to choose from.
- Editable or Non-Editable:
JComboBox
can be configured to either allow the user to type a value (editable) or limit them to selecting from the dropdown list (non-editable). - Customizable Items: You can add custom items, including any objects, to the combo box.
- Event Handling: You can register listeners to capture the selection event, enabling you to perform actions based on the user’s choice.
Basic Usage Example:
import javax.swing.*;
public class ComboBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JComboBox Example");
String[] items = {"Apple", "Banana", "Orange"};
JComboBox<String> comboBox = new JComboBox<>(items);
comboBox.addActionListener(e -> {
String selectedItem = (String) comboBox.getSelectedItem();
System.out.println("Selected item: " + selectedItem);
});
frame.add(comboBox);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Key Methods:
- addItem(Object item): Adds an item to the combo box.
- removeItem(Object item): Removes a specific item.
- getSelectedItem(): Returns the currently selected item.
- setEditable(boolean editable): Sets whether the combo box allows user input.
In summary, JComboBox
is a versatile Swing component used to provide a drop-down list of options, making it a useful tool for user interfaces where a choice from a limited set of options is required.