import java.awt.*;
import javax.swing.*;
public class JComboBoxTest extends JFrame {
JComboBox<String> jc = new JComboBox<>(new MyComboBox());
JLabel jl = new JLabel("请选择证件");
public JComboBoxTest() {
setTitle("在窗体中使用列表组件");
setSize(500, 400);
setVisible(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(jl);
c.add(jc);
}
public static void main(String[] args) {
new JComboBoxTest();
}
class MyComboBox extends AbstractListModel<String> implements ComboBoxModel<String> {
String selectedItem = null;
String[] test = { "身份证", "学生证", "军官证", "工人正" };
public String getElementAt(int index) {
return test[index];
}
public int getSize() {
return test.length;
}
public void setSelectedItem(Object item) {
selectedItem = (String) item;
}
public Object getSelectedItem() {
return selectedItem;
}
public int getIndex() {
for (int i = 0; i < test.length; i++) {
if (test[i].equals(getSelectedItem()))
return i;
}
return 0;
}
}
}
疑问:String selectedItem = null;这段代码有什么作用?
为什么要获取test字符数组中的索引值和长度?
最后一点for循环是做什么用的?