views:

121

answers:

3

I would like to be able to populate a jcombobox from a textfile. I am using NetBeans 6.9. Any suggestions would be appreciated. Thanks.

+2  A: 

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);
I82Much
+2  A: 

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.

trashgod
+1  A: 

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

camickr