[英]How do I populate JComboBox from a text file?
如何從文本文件填充JComboBox
?
非常模糊的問題。 您是說要每行輸入一個嗎? 如果是這樣,則要使用BufferedReader之類的東西,請讀取所有行,並將它們保存為String數組。 創建一個新的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);
將您的需求分解為單獨的步驟,代碼將如下:
1)從文件中讀取一行數據2)使用JComboBox addItem(...)方法將數據添加到組合框中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.