在这个SSCCE中为我工作:
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.SwingUtilities;
import javax.swing.UnsupportedLookAndFeelException;
public class TestComboBox {
private int count = 0;
protected void initUI() {
final JFrame frame = new JFrame(TestComboBox.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComboBox comboBox = new JComboBox(new Object[] { "Something", "Stuff", "Beep" });
JButton add = new JButton("Add item");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
comboBox.addItem("Item-" + count++);
}
});
frame.add(comboBox);
frame.add(add, BorderLayout.SOUTH);
frame.pack();
frame.setBounds(50, 50, 300, frame.getHeight());
frame.setVisible(true);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestComboBox().initUI();
}
});
}
}