如何从文本文件填充 JComboBox?

发布于 2024-09-08 06:45:21 字数 40 浏览 0 评论 0原文

如何从文本文件填充 JComboBox

How do I populate a JComboBox from a text file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沧笙踏歌 2024-09-15 06:45:21

很模糊的问题。您是说您想要每行一个条目吗?如果是这样,您想使用类似 BufferedReader 的东西,读取所有行,将它们保存为字符串数组。创建一个新的 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);

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);
絕版丫頭 2024-09-15 06:45:21

下面是一个示例,它读取属性文件以获取键(用于组合)和值(对于文本区域)。请参阅中的枚举规则

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.

夜唯美灬不弃 2024-09-15 06:45:21

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文