如何在 Java 运行时向 JComboBox 中添加项
以下是一个示例,用于在 Java 中在运行时向 JComboBox 中添加项
示例
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; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComboBox<String> combo = new JComboBox<>(new String[] { "One","Two", "Three","Four","Five", "Six" }); JButton add = new JButton("Add"); add.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { combo.addItem("New"); } }); frame.add(combo); frame.add(add, BorderLayout.NORTH); frame.setSize(500, 100); frame.setVisible(true); } }
输出
现在,我们有以下项
现在,单击上方的“添加”以在运行时添加新项。单击后,新项将显示在底部,如下图所示
广告