Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从文本文件填充JComboBox?_Java_Text Files_Jcombobox_Populate - Fatal编程技术网

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

Java 如何从文本文件填充JComboBox?,java,text-files,jcombobox,populate,Java,Text Files,Jcombobox,Populate,如何从文本文件填充JComboBox?非常模糊的问题。你是说你想要每行一个条目吗?如果要使用BufferedReader之类的东西,请读取所有行,并将它们另存为字符串数组。创建一个新的JComboBox,传入该字符串构造函数 BufferedReader input = new BufferedReader(new FileReader(filePath)); List<String> strings = new ArrayList<String>(); try {

如何从文本文件填充
JComboBox

非常模糊的问题。你是说你想要每行一个条目吗?如果要使用BufferedReader之类的东西,请读取所有行,并将它们另存为字符串数组。创建一个新的JComboBox,传入该字符串构造函数

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);
BufferedReader input=new BufferedReader(new FileReader(filePath));
列表字符串=新的ArrayList();
试一试{
字符串行=null;
而((line=input.readLine())!=null){
字符串。添加(行);
}
}
catch(filenotfounde异常){
System.err.println(“错误,文件“+filePath+”不存在。”);
}
最后{
input.close();
}
String[]lineArray=strings.toArray(新字符串[]{});
JComboBox组合框=新的JComboBox(线性阵列);

下面是一个函数,它读取属性文件以获取键(用于组合)和值(用于文本区域)。请参阅。

中的
枚举规则
,将您的需求分解为单独的步骤,代码如下所示:

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