Java Jcombobox从具有2个映射值的文本文件读取
我有一个如下所示的文本文件:Java Jcombobox从具有2个映射值的文本文件读取,java,Java,我有一个如下所示的文本文件: ap apple og orange gp grape 我希望jcombobox在下拉列表中显示apple、orange、grape,但当选择它时,输出ap,og和gp您可以使用vector存储字符串的第一部分。然后从combobox中获取getselected索引。然后从同一索引中从vector中取出值。vector索引和jcombobox索引已映射 在将第一部分添加到vector时,应该将第二部分添加到combobox v1.add(split[0]); jC
ap apple
og orange
gp grape
我希望jcombobox在下拉列表中显示
apple、orange、grape
,但当选择它时,输出ap
,og
和gp
您可以使用vector存储字符串的第一部分。然后从combobox中获取getselected
索引。然后从同一索引中从vector中取出值。vector索引和jcombobox索引已映射
在将第一部分添加到vector时,应该将第二部分添加到combobox
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);
您可以制作自己的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);
私有静态类{
公共最终字符串id;
公共最终字符串名;
公共水果(字符串id、字符串名称){
this.id=id;
this.name=名称;
}
@凌驾
公共字符串toString(){
返回名称;
}
}
私有最终列表结果=Arrays.asList(
新水果(“ap”、“苹果”),
新水果(“og”、“橙色”),
新水果(“gp”、“葡萄”)
);
DefaultComboxModel=新的DefaultComboxModel();
用于(水果:水果){
模型.附加元素(水果);
}
jcombox1.setModel(model);
在这里,我只是让组合框在getSelectedItem上返回水果。使用映射可以很容易地通过重写方法返回短ID。没有什么特别的简单工作,是关于自定义渲染器的,投票关闭,因为太宽了。创建一个类来保存这两个值。重写该类中的
toString()
,只返回第二个值。阅读文件,拆分每一行并从类中创建一个对象。对于您阅读的每一行,将作为类的实例添加到组合框中。这样,在选择时,您可以访问<代码> AP <代码>或<代码>苹果<代码>。如果您需要考虑使用“试用资源”语句:那么考虑更好地考虑下拉列表的Vector VS映射必须以字母顺序显示。棘手的部分是V1.Add(StRe[ 0)];JCombox1.附加项(拆分[1]);您应该将第一部分添加到组合框,然后再添加到vector