本示例演示如何使用insertItemAt(Object o, int index)andaddItem(Object o)方法将项目添加到组合框列表中的特定位置或列表的末尾。在代码中,我们还将学习如何使用的removeItemAt(int index)方法和removeAllItems()方法从列表中删除一项或所有项JComboBox。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class ComboBoxAddRemoveItem extends JFrame { public ComboBoxAddRemoveItem() { initialize(); } private void initialize() { setSize(300, 300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.LEFT)); String[] items = new String[] {"Two", "Four", "Six", "Eight"}; final JComboBox comboBox = new JComboBox(items); getContentPane().add(comboBox); JButton button1 = new JButton("Add One"); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 在列表的开头添加项目“One” comboBox.insertItemAt("One", 0); } }); JButton button2 = new JButton("Add Five and Nine"); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { comboBox.insertItemAt("Five", 3); comboBox.addItem("Nine"); } }); getContentPane().add(button1); getContentPane().add(button2); JButton remove1 = new JButton("Remove Eight and Last"); remove1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 从列表中删除八个项目和最后一个项目。 comboBox.removeItemAt(5); comboBox.removeItemAt(comboBox.getItemCount() - 1); } }); JButton remove2 = new JButton("Remove All"); remove2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { comboBox.removeAllItems(); } }); getContentPane().add(remove1); getContentPane().add(remove2); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ComboBoxAddRemoveItem().setVisible(true); } }); } }