This example demonstrate how to add an items into a specific position in the combo box list or at the end of the list using the insertItemAt(Object o, int index)
and addItem(Object o)
method. In the code we also learn how to remove one or all items from the list using removeItemAt(int index)
method and removeAllItems()
method of JComboBox
.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class ComboBoxAddRemoveItem extends JFrame {
public ComboBoxAddRemoveItem() {
initialize();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new ComboBoxAddRemoveItem().setVisible(true));
}
private void initialize() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
String[] items = new String[]{"Two", "Four", "Six", "Eight"};
final JComboBox<String> comboBox = new JComboBox<>(items);
getContentPane().add(comboBox);
JButton button1 = new JButton("Add One");
button1.addActionListener(e -> {
// Add item "One" at the beginning of the list.
comboBox.insertItemAt("One", 0);
});
JButton button2 = new JButton("Add Five and Nine");
button2.addActionListener(e -> {
// Add item Five on the third index and Nine at the end of the
// list.
comboBox.insertItemAt("Five", 3);
comboBox.addItem("Nine");
});
getContentPane().add(button1);
getContentPane().add(button2);
JButton remove1 = new JButton("Remove Eight and Last");
remove1.addActionListener(e -> {
// Remove the Eight item and the last item from the list.
comboBox.removeItemAt(5);
comboBox.removeItemAt(comboBox.getItemCount() - 1);
});
JButton remove2 = new JButton("Remove All");
remove2.addActionListener(e -> comboBox.removeAllItems());
getContentPane().add(remove1);
getContentPane().add(remove2);
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Useful one.
Thank you very use full for me
Thanks a lot, very helpful.
Great!! Very helpful