从文本文件填充JCombobox

时间:2013-01-20 11:18:13

标签: java swing netbeans file-io jcombobox

我已经看到一个较旧的问题,答案是下面的代码,但如果我使用netbeans,我已经设计了我的comboBox。所以我认为(我想象的是Java和netbeans中的新东西!)代码的最后一行应该改变,我在哪里插入这段代码?

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); 

2 个答案:

答案 0 :(得分:6)

1.这些代码行无用

List<String> strings = new ArrayList<String>();
String[] lineArray = strings.toArray(new String[]{});
JComboBox comboBox = new JComboBox(lineArray); 

2.直接向DefaultComboBoxModel添加新项目,也可以对项目进行排序

3.可以EDT issue read Concurency in Swing,使用SwingWorker for loading Items from File

答案 1 :(得分:0)

您可以通过调用setModel方法来更改现有的JComboBox项目。

对于它的价值,你可能会发现Files.readAllLines方法更容易使用:

try {
    final List<String> lines = Files.readAllLines(Paths.get(filePath),
        Charset.defaultCharset());

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            comboBox.setModel(
                new DefaultComboBoxModel<String>(
                    lines.toArray(new String[0])));
        }
    });
} catch (IOException e) {
    e.printStackTrace();
}