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

Java 如何将文本文件中的行复制到JComboBox中?,java,swing,jcombobox,filereader,Java,Swing,Jcombobox,Filereader,我试图将文本文件的每一行复制到jcomboBox中,但它只显示jcomboBox中文本文件的第一行……我不明白为什么。 你能告诉我怎么了吗 (...) BufferedReader in; String read; try { in = new BufferedReader(new FileReader("D:/File.txt")); read = in.readLine(); lines[

我试图将文本文件的每一行复制到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);            
    }
(...)

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

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

注意:我假设数组
足够大

您只读取文件的第一行。所以JCombobox里没有更多了。您应该花一段时间阅读所有行,直到读到结尾。

替换

read = in.readLine();

lines[w]=read;


可能是因为你只看了第一行?!:)
while((read = in.readLine())!=null){
    lines[w++]=read;
}