Java Swing - 如何在JComboBox上添加項目運行時
我們想知道如何在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 Main {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox<String> comboBox = new JComboBox<>(new String[] { "Something",
"Stuff", "Beep" });
JButton add = new JButton("Add item");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
comboBox.addItem("Item");
}
});
frame.add(comboBox);
frame.add(add, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}