我现在正在制作一个应用程序,现在我需要用从 arrayList 类型中的另一个类获得的所有值填充组合框。
这是我用来填充组合框的代码:
public void setComboBox(){
MessageConsole mc = new MessageConsole(textArea);
//The redirectOut will redirect the text from the System.out.prtnln to the text area.
mc.redirectOut();
List<String> arrayList = new ArrayList<String>();
if(gf.loadCombo("config") != null){
arrayList.addAll(gf.loadCombo("config"));
for (int i = 0; i < arrayList.size(); i++) {
String s = arrayList.get(i);
configName.removeItem(s);
configName.addItem(s);
}
}
}
这是另一个类的代码:
public Collection<String> loadCombo(String property) {
//Check if the property file is present in the given directory.
if(cf.checkProperty()==true){
//Check is there are any properties saved in the property file.
if(cf.getProperty() != null){
Properties prop = new Properties();
FileInputStream fis;
try {
fis = new FileInputStream("config.properties");
prop.load(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Check if the properties match with the entered configuration.
List<String> arrayList = new ArrayList<String>();
arrayList.addAll(cf.getProperty());
Collection<String> propertyList = new ArrayList<String>();
for (int i = 0; i < arrayList.size(); i++) {
String s = arrayList.get(i);
if(s.startsWith(property)){
System.out.println("This value has been added to the arrayList from the other class: "+s);
propertyList.add(cf.getPropertyValue(s));
}
}
return propertyList;
}
//The system prints a message of the missing properties.
else{
System.out.println("You need to save a configuration first.");
}
}
//The system prints a message of the missing property file.
else{
System.out.println("The property file is either missing or could not be found. in de Load class");
}
return null;
}
以下是结果截图:
正如您所看到的,所有值都作为 1 个长字符串“[3, 2, 1]”添加到组合框中。谁能告诉我为什么会发生这种情况?
提前致谢,
洛达努德
附注我希望这是提出问题的正确方式,并且希望我的问题足够清楚,让每个人都能理解。
最佳答案
乍一看,问题可能是以下两件事之一:
- 值“[3 2 1]”是从
loadCombo
方法返回的。更具体地说,来自cf.getProperty()
。从上下文中并不清楚cf
是什么。 - 值“[3 2 1]”已在代码中的其他位置添加到组合框中。如果出现这种情况,请尝试使用
configName.removeAllItems()
,而不是先删除集合中的每个项目,然后再添加。
此外,在 loadCombo
方法中,您将 config.properties 文件加载到 Properties 对象中,然后不对其执行任何操作。看来您的意图是从该文件而不是 cf
对象加载配置属性。
关于java - ComboBox 将所有值加在一起作为一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13179704/