Basically what I’m doing here is importing the contents of a text file into user input fields (there are 7 of them. I run a loop to go through them for command [i]. The code works fine within the console, but it wont work for the GUI as it only inputs the last line for each field. Have you got any clue what the problem is? Here is the UI:
http://imageshack.us/f/692/21778853.jpg
As you can see, it prints into the console fine, but when I import data by clicking import on the GUI then it just puts the last command of the txt file
My code is:
final JTextField Command[];//Create one dimensional array
Command = new JTextField[8];//Declare Command as a JTextField
for (int i = 1; i < 8; i++)//Run the loop through each selection
{
Command[i] = new JTextField(i);//Read through each text field
}
//Add user input fields including their absolute position on the panel
Command[1].setText("Please enter the commands...");//Starting text
Command[1].setBounds(121, 13, 236, 25);//Set the position of the text field
getContentPane().add(Command[1]);//Add this text field to the content
Command[2].setBounds(121, 47, 236, 25);/fsdfsdf
getContentPane().add(Command[2]);
Command[3].setBounds(121, 83, 236, 25);/fasdfasd
getContentPane().add(Command[3]);
Command[4].setBounds(121, 119, 236, 25);/fsfasdasdf
getContentPane().add(Command[4]);
Command[5].setBounds(121, 155, 236, 25);
getContentPane().add(Command[5]);
Command[6].setBounds(121, 191, 236, 25);
getContentPane().add(Command[6]);
Command[7].setBounds(121, 227, 236, 25);
getContentPane().add(Command[7]);
//IMPORT FILE
JMenuItem Import = new JMenuItem("Import");
File.add(Import);
Import.addActionListener(new ActionListener() {//Call up ActionListener function
public void actionPerformed(ActionEvent arg0) {//Event handler
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader("W:\\EclipsePortable\\Data\\workspace2\\" +
"RobotController\\src\\RobotController\\Import commands.txt"));
try {
String line = null; //not declared within while loop
while (( line = input.readLine()) != null) {
System.out.println(line);//Print the lines
for(int i = 1; i < 8; i++) {
Command[i].setText(line);
}
}}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}});`
So, in your file import code you are doing this…
Which is applying the current line of text to ALL the fields (the same line of text for all the fields), which means by the time you finish reading the file, you’ve only got the last line of the file.
Instead, I would keep a reference to the field index and increment in each line read
Added Example