开发者

How can I copy lines from a text file into a JComboBox?

开发者 https://www.devze.com 2023-03-28 08:45 出处:网络
I\'m trying to copy each line of a text file into a jcomboBox, but it displays only the first line of the text file in the jcomboBox...I don\'t understand why.

I'm trying to copy each line of a text file into a jcomboBox, but it displays only the first line of the text file in the jcomboBox...I don't understand why. Can you please explain me what's wrong?

(...)
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.pri开发者_开发技巧ntln("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);            
    }
(...)


That's because you read only the first line and close the file, consider:

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

Note: I assume the array lines is big enough


You're only reading the first line of the file. So there can't be more in the JCombobox. You should use a while and read all lines till you reach the end.


replace

read = in.readLine();

lines[w]=read;

with

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

精彩评论

暂无评论...
验证码 换一张
取 消