我有看起來像下面的文本文件:的JComboBox從文本文件閱讀與2映射值
ap apple
og orange
gp grape
我想JComboBox時顯示在下拉apple,orange,grape
但是,當選擇它輸出ap
,og
和gp
我有看起來像下面的文本文件:的JComboBox從文本文件閱讀與2映射值
ap apple
og orange
gp grape
我想JComboBox時顯示在下拉apple,orange,grape
但是,當選擇它輸出ap
,og
和gp
您可以使用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);
考慮使用try-with-resources聲明:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose .html – Tom 2014-10-17 10:16:31
所以考慮下拉列表時,考慮更好的矢量與地圖必須按字母順序顯示。 – newbieprogrammer 2014-10-17 10:51:52
棘手的部分是 v1.add(split [0]); jComboBox1.addItem(split [1]); 你應該添加第一部分combobox下一部分向量 – 2014-10-17 10:58:08
你可以讓你自己的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。使用地圖可以輕鬆地返回短ID。通過重寫方法。
+1 yup .......... – 2014-10-17 10:24:23
沒什麼特別的,簡單的工作,是關於自定義渲染器,投票關閉太寬 – mKorbel 2014-10-17 10:05:24
創建一個類來保存這兩個值。重寫該類中的'toString()'以返回第二個值。閱讀文件,分割每一行,並從你的班級創建一個對象。作爲類的實例,添加到您閱讀的每一行的組合框中。這樣選擇後,如果需要,可以使用'ap'或'apple' – 2014-10-17 10:15:22