java 如何从文本文件填充 JComboBox?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3173149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:41:15  来源:igfitidea点击:

How do I populate JComboBox from a text file?

javatext-filesjcomboboxpopulate

提问by Magwich

How do I populate a JComboBoxfrom a text file?

如何JComboBox从文本文件填充 a ?

回答by I82Much

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);

回答by trashgod

Here's an examplethat reads a properties file to get keys (for the combo) and values (for a text area). See enum Rulein the source.

这是一个读取属性文件以获取键(对于组合)和值(对于文本区域)的示例。请参见enum Rule

回答by camickr

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(...) 方法将数据添加到组合框