如何在 Java 中處理 JComboBox 的操作事件?


以下是處理 JComboBox 操作事件的 Java 示例

示例

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

輸出

現在,我們有以下專案

現在,點選上面的“新增”,以在執行時新增新的專案。點選後,新的專案將顯示在底部,如以下螢幕截圖所示

更新時間: 2019-07-30

699 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始:
廣告
© . All rights reserved.