简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM