下拉列表 JComboBox
一、基本用法
-
创建 JComboBox
JComboBox<String> colorList = new JComboBox<>();
-
添加数据项
colorList.addItem("红色"); colorList.addItem("蓝色"); colorList.addItem("绿色");
addItem(T),T的类型在创建时指定,这里是String类型,也就说每一项Item的数据类型是 String
-
按索引访问
getSelectedIndex(); //获取选中项的索引 setSelectedIndex(int index); //设置选中项 removeItemAt(int index); //按索引删除
-
按数据项访问
getSelectedItem(); setSelectedItem(); removeItem();
-
事件处理
还是ActionListener
代码:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Demo {
public static void main(String[] args) {
MyFrame2 frame = new MyFrame2("Demo");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class MyFrame2 extends JFrame{
JLabel label = new JLabel("一个案例,This is...");
JComboBox<OptionList> comboBox = new JComboBox<>();
public MyFrame2(String title) {
super(title);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(comboBox);
contentPane.add(label);
comboBox.addItem(new OptionList("红色", Color.RED));
comboBox.addItem(new OptionList("蓝色", Color.BLUE));
comboBox.addItem(new OptionList("绿色", Color.GREEN));
updateColor();
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateColor();
}
});
}
public void updateColor() {
OptionList op = (OptionList)comboBox.getSelectedItem();
label.setForeground(op.getColor());
}
private class OptionList {
private String text;
private Color color;
public OptionList(String text, Color color) {
this.text = text;
this.color = color;
}
//重写toString方法,以便Swing进行展示
public String toString() {
return this.text;
}
public String getText() {
return text;
}
public Color getColor() {
return color;
}
}
}
输出: