如何在 Java 中顯示 JComboBox 中的條目


以下是一個在 Java 中顯示 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;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new BorderLayout());
      String[] strArr = new String[] { "Laptop", "Mobile", "Desktop", "Tablet" };
      JComboBox<String> comboBox = new JComboBox<>(strArr);
      panel.add(comboBox, BorderLayout.NORTH);
      JTextArea text = new JTextArea(5, 5);
      panel.add(text, BorderLayout.CENTER);
      JButton btn = new JButton("Click");
      btn.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            text.setText((String) comboBox.getSelectedItem());
            comboBox.setSelectedIndex(0);
         }
      });
      panel.add(btn, BorderLayout.SOUTH);
      JFrame frame = new JFrame();
      frame.add(panel);
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

輸出如下,顯示第一個專案

輸出

現在,選擇第二個專案(移動)並按下“單擊”按鈕。將顯示以下內容

更新日期:30-Jul-2019

687 次瀏覽

開啟 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.