How do I populate a JComboBox
from a text file?
如何从文本文件中填充JComboBox?
3 个解决方案
#1
4
Very vague question. Are you saying you want one entry per line? If so you want to use something like a BufferedReader, read all the lines, save them as a String array. Create a new JComboBox passing in that String constructor.
很模糊的问题。你是说你想要每行一个条目吗?如果是这样,你想使用类似BufferedReader的东西,读取所有行,将它们保存为String数组。在String构造函数中创建一个新的JComboBox。
BufferedReader input = new BufferedReader(new FileReader(filePath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while (( line = input.readLine()) != null){
strings.add(line);
}
}
catch (FileNotFoundException e) {
System.err.println("Error, file " + filePath + " didn't exist.");
}
finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
JComboBox comboBox = new JComboBox(lineArray);
#2
#3
1
Break down your requirements into separate steps and the code will follow:
将您的需求分解为单独的步骤,代码将遵循:
1) read a line of data from the file 2) use the JComboBox addItem(...) method to add the data to the combo box
1)从文件中读取一行数据2)使用JComboBox addItem(...)方法将数据添加到组合框中
#1
4
Very vague question. Are you saying you want one entry per line? If so you want to use something like a BufferedReader, read all the lines, save them as a String array. Create a new JComboBox passing in that String constructor.
很模糊的问题。你是说你想要每行一个条目吗?如果是这样,你想使用类似BufferedReader的东西,读取所有行,将它们保存为String数组。在String构造函数中创建一个新的JComboBox。
BufferedReader input = new BufferedReader(new FileReader(filePath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while (( line = input.readLine()) != null){
strings.add(line);
}
}
catch (FileNotFoundException e) {
System.err.println("Error, file " + filePath + " didn't exist.");
}
finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
JComboBox comboBox = new JComboBox(lineArray);
#2
2
Here's an example that reads a properties file to get keys (for the combo) and values (for a text area). See enum Rule
in the source.
这是一个示例,它读取属性文件以获取键(对于组合)和值(对于文本区域)。请参阅源代码中的枚举规则。
#3
1
Break down your requirements into separate steps and the code will follow:
将您的需求分解为单独的步骤,代码将遵循:
1) read a line of data from the file 2) use the JComboBox addItem(...) method to add the data to the combo box
1)从文件中读取一行数据2)使用JComboBox addItem(...)方法将数据添加到组合框中