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

如何从文本文件中填充JComboBox

很模糊的问题。 你是说你想要每行一个条目吗? 如果是这样,你想使用类似BufferedReader的东西,读取所有行,将它们保存为String数组。 在String构造函数中创建一个新的JComboBox。

 BufferedReader input = new BufferedReader(new FileReader(filePath)); List strings = new ArrayList(); 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); 

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

将您的需求分解为单独的步骤,代码将遵循:

1)从文件中读取一行数据2)使用JComboBox addItem(…)方法将数据添加到combobox中