设置下拉列表框大小以及位置,为下拉列表框添加选项,将下拉列表框加入到JFrame窗口,返回当前所选项,添加选中状态改变的监听器
import javax.swing.*;
import java.awt.event.*;
public class lll {
public static void main(String[] args) {
JFrame JF = new JFrame("窗口");
JF.setSize(500, 500);
JF.setLocationRelativeTo(null);
JF.setDefaultCloseOperation(3);
JPanel JP = new JPanel();
JLabel JL = new JLabel("选择:");
JP.add(JL);
String[] a = new String[]{"A", "B", "C", "D" , "E"};
JComboBox JC = new JComboBox(a);
JC.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.SELECTED == e.getStateChange()) {
System.out.println("你选择了:"+JC.getSelectedItem()+"是第"+ (JC.getSelectedIndex()+1)+"个选项");
}
}
});
JC.setSelectedIndex(0);
JP.add(JC);
JF.setContentPane(JP);
JF.setVisible(true);
}
}