如何通过索引预选 JComboBox 项?
以下示例演示如何通过索引在 Java 中预选 JComboBox 项。在此示例中,我们默认选择第 3 个项,即每当 Swing 程序运行时,将显示第 3 个项而不是第 1 个项。
示例
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; public class SwingDemo { public static void main(String[] args) { JPanel panel = new JPanel(new BorderLayout()); String[] strArr = new String[] { "Laptop", "Mobile", "Desktop", "Tablet" }; JComboBox<String> comboBox = new JComboBox<>(strArr); panel.add(comboBox, BorderLayout.NORTH); JTextArea text = new JTextArea(5, 5); panel.add(text, BorderLayout.CENTER); JButton btn = new JButton("Click"); // selecting the index comboBox.setSelectedIndex(2); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { text.setText((String) comboBox.getSelectedItem()); comboBox.setSelectedIndex(0); } }); panel.add(btn, BorderLayout.SOUTH); JFrame frame = new JFrame(); frame.add(panel); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
输出如下所示。默认选中第 3 个项(索引为 2)
输出
在此处,你可以检查所有项
广告