如何在 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);
}
}输出如下,显示第一个项目
输出

现在,选择第二个项目(移动)并按下“单击”按钮。将显示以下内容

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP