本示例演示JComboBox的getItemCount()方法的使用getItemAt(int index)以及如何获取组合框中的项目数以及如何获取每个项目。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class ComboBoxGetItems extends JFrame { public ComboBoxGetItems() { initialize(); } private void initialize() { setSize(300, 300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.LEFT)); // 创建带有等级作为值的JComboBox; 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(new ActionListener() { public void actionPerformed(ActionEvent e) { //在下拉列表框中获取项目数。重复 // 从零到组合框项目的数量,并获取每个项目 // 指定索引的。 // // 在此示例中,我们只是将项目放置在StringBuilder中 // 并稍后打印。 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.toString() + "]"); } }); getContentPane().add(button); getContentPane().add(label); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ComboBoxGetItems().setVisible(true); } }); } }