基本上,我在这里所做的是将文本文件的内容导入到用户输入字段中(共有7个。我为命令[I]运行一个循环来遍历它们。代码在控制台中运行良好,但对GUI不起作用,因为它只为每个字段输入最后一行。你知道问题是什么吗?下面是UI:
http://imageshack.us/f/692/21778853.jpg
正如您所看到的,它可以很好地打印到控制台中,但当我通过在GUI上单击导入来导入数据时,它只会放入txt文件的最后一个命令
我的代码是:
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();
}
}});`
因此,在文件导入代码中,您正在执行以下操作。。。
for(int i = 1; i < 8; i++) {
Command[i].setText(line);
这是将当前的文本行应用于所有字段(所有字段都是同一行文本),这意味着当你完成读取文件时,你只得到了文件的最后一行。
相反,我会在读取的每一行中保留字段索引和增量的参考
添加示例
String line = null; //not declared within while loop
int fieldIndex = 0;
while (( line = input.readLine()) != null) {
System.out.println(line);//Print
Command[fieldIndex].setText(line);
fieldIndex++
if (fieldIndex > 7) {
break;
}