如何在 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); } }
輸出
現在,我們有以下項
現在,單擊上方的“新增”以在執行時新增新項。單擊後,新項將顯示在底部,如下圖所示
廣告