繁体   English   中英

如何从文本文件填充JComboBox?

[英]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);

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM