[英]How do I populate JComboBox from a text file?
如何从文本文件填充JComboBox
?
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.
如果是这样,则要使用BufferedReader之类的东西,请读取所有行,并将它们保存为String数组。 Create a new JComboBox passing in that String constructor.
创建一个新的JComboBox传入该String构造函数。
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);
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(...)方法将数据添加到组合框中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.