gpt4 book ai didi

java - 设置UI内容仅添加最后一行

转载 作者:行者123 更新时间:2023-12-01 14:52:49 24 4
gpt4 key购买 nike

基本上,我在这里所做的是将文本文件的内容导入到用户输入字段中(其中有 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;
}

关于java - 设置UI内容仅添加最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14675450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com