问题
Possible Duplicate:
How do I populate JComboBox from a text file?
I am new to programming Java with only 2 months of experience. Can anyone help me to populate a JComboBox
with a text file, consisting of 5 lines? I have looked at code on Google, but I keep getting errors.
回答1:
private void populate() {
String[] lines;
lines = readFile();
jComboBox1.removeAllItems();
for (String str : lines) {
jComboBox1.addItem(str);
}
}
Here is readFile(). From this site
private String[] readFile() {
ArrayList<String> arr = new ArrayList<>();
try {
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
arr.add(strLine);
}
in.close();
} catch (Exception e) {
}
return arr.toArray(new String[arr.size()]);
}
来源:https://stackoverflow.com/questions/14368268/populating-jcombobox-with-a-text-file