简体   繁体   English

如何从文本文件填充JComboBox?

[英]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);

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 . 请参阅源代码中的 enum Rule

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM