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;
}
精彩评论