首页javajcomboboxJava Swing - 如何在JComboBox上添加项目运行时

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);
  }
}