How do I populate JComboBox from a text file?

女生的网名这么多〃 提交于 2019-11-26 14:49:06

问题


How do I populate a JComboBox from a text file?


回答1:


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 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:


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:


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



来源:https://stackoverflow.com/questions/3173149/how-do-i-populate-jcombobox-from-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!