This example demonstrate the use of JComboBox
‘s getItemCount()
method and getItemAt(int index)
to get the number of items inside the combo box and how to obtain each of them.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class ComboBoxGetItems extends JFrame {
public ComboBoxGetItems() {
initialize();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new ComboBoxGetItems().setVisible(true));
}
private void initialize() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
// Create JComboBox with grade as the values;
String[] items = new String[]{"A", "B", "C", "D", "E", "F"};
final JComboBox<String> gradeCombo = new JComboBox<>(items);
getContentPane().add(gradeCombo);
JButton button = new JButton("Get Items");
final JLabel label = new JLabel("Items count: ");
button.addActionListener(e -> {
// Get the number of items in the combo box drop-down. Iterate
// from zero to the number of combo box items and get each item
// of the specified index.
//
// In this example we just place the items inside a StringBuilder
// and print it later on.
int count = gradeCombo.getItemCount();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append(gradeCombo.getItemAt(i));
if (i < count - 1) {
builder.append(", ");
}
}
label.setText("Item count: " + count + "; ["
+ builder + "]");
});
getContentPane().add(button);
getContentPane().add(label);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024