我有一个文本文件,如下所示:
ap apple
og orange
gp grape
我希望jcombobox在下拉列表中显示apple,orange,grape
,但选择后会输出ap
,og
和gp
答案 0 :(得分:1)
你可以使用vector来存储String的第一部分。然后从combobox获取getselected
索引。然后从相同索引的向量中取出值.vector索引和jcombobox索引已映射。
你应该将第二部分添加到组合框中,同时将第一部分添加到矢量
v1.add(split[0]);
jComboBox1.addItem(split[1]);
这是示例代码
Vector v1;//field
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("test.txt")));
String line;
v1=new Vector();
while ((line = br.readLine()) != null) {
String[] split = line.split(" ");
v1.add(split[0]);
jComboBox1.addItem(split[1]);
}
br.close();
} catch (Exception ex) {
ex.printStackTrace();
}
执行组合框动作
String get = (String) v1.get(jComboBox1.getSelectedIndex());
System.out.println(get);
答案 1 :(得分:1)
您可以制作自己的ComboBoxModel。
private static class Fruit {
public final String id;
public final String name;
public Fruit(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return name;
}
}
private final List<Fruit> fruits = Arrays.asList(
new Fruit("ap", "apple"),
new Fruit("og", "orange"),
new Fruit("gp", "grape")
);
DefaultComboBoxModel<Fruit> model = new DefaultComboBoxModel<>();
for (Fruit fruit : fruits) {
model.addElement(fruit);
}
jComboBox1.setModel(model);
这里我让ComboBox在getSelectedItem上返回Fruit。使用Map可以轻松返回短ID。通过重写方法。