To empty a JComboBox
in Java, you can use the removeAllItems()
method of the JComboBox
class.
Here's an example of how to empty a JComboBox
:
import javax.swing.*; public class ComboBoxClearer extends JFrame { public ComboBoxClearer() { // Create a combo box and add some items to it JComboBox<String> comboBox = new JComboBox<>(); comboBox.addItem("Item 1"); comboBox.addItem("Item 2"); comboBox.addItem("Item 3"); // Add a button to clear the combo box JButton clearButton = new JButton("Clear"); clearButton.addActionListener(e -> comboBox.removeAllItems()); // Add the combo box and button to the frame add(comboBox); add(clearButton); // Set the size and layout of the frame setSize(200, 100); setLayout(new FlowLayout()); setVisible(true); } public static void main(String[] args) { new ComboBoxClearer(); } }
In this example, a JComboBox
is created and some items are added to it using the addItem()
method. A JButton
is also created with the label "Clear", and an action listener is added to the button that calls the removeAllItems()
method of the combo box when the button is clicked.
This example demonstrates how to empty a JComboBox
by removing all of its items. You can use the removeAllItems()
method to clear the combo box at any time, either before or after it is displayed.