如何将文本文件中的行复制到JComboBox中?

时间:2011-08-16 22:59:18

标签: java swing jcombobox filereader

我正在尝试将文本文件的每一行复制到jcomboBox中,但它只显示jcomboBox中文本文件的第一行...我不明白为什么。 你能解释一下我的错误吗?

(...)
BufferedReader in;
    String read;

        try {
            in = new BufferedReader(new FileReader("D:/File.txt"));


            read = in.readLine();

            lines[w]=read;

             ++w;

            in.close();
        }catch(IOException e){
            System.out.println("There was a problem:" + e);
        }

    combo1 = new JComboBox(lines);

    combo1.setPreferredSize(new Dimension(100,20));
    combo1.setForeground(Color.blue);


    JPanel top = new JPanel();
    top.add(label);
    top.add(combo1);

    combo1.addActionListener(new ActionFichiers());

    container.add(top, BorderLayout.NORTH);
    this.setContentPane(container);
    this.setVisible(true);            
    }
(...)

3 个答案:

答案 0 :(得分:5)

那是因为您只读取第一行并关闭文件,请考虑:

     try {
        in = new BufferedReader(new FileReader("D:/File.txt"));
        while((read = in.readLine()) != null){
            lines[w]=read;
           ++w;
        }
        in.close();
    }catch(IOException e){
        System.out.println("There was a problem:" + e);
    }

注意:我假设数组lines足够大

答案 1 :(得分:4)

您只是在阅读文件的第一行。所以在JCombobox中不可能有更多。您应该使用一段时间并阅读所有行,直到结束。

答案 2 :(得分:4)

替换

read = in.readLine();

lines[w]=read;

while((read = in.readLine())!=null){
    lines[w++]=read;
}