JavaFX读取文本文件并将其显示在多个文本字段中

huangapple go评论60阅读模式
英文:

JavaFX reading a text file and displaying it to multiple text fields

问题

I have a text file with 4 lines of random words, line for line, and I need to be able to read each line and display it to its text field (First line goes into first text field, etc), but it is only reading the last line and displaying it into any text field.

"myfile.txt"
one

two

three

onetwothree

TextField label1Text = new TextField();
TextField label2Text = new TextField();
TextField label3Text = new TextField();

load.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent l) {
        
        String line = ""; 
        try {
        BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"));
              
            while ((line = reader.readLine()) != null) {
           
              label1Text.setText(line);
              label2Text.setText(line);
              label3Text.setText(line);
              labelO2Text.setText(line);   
            }
            
        } 

        catch (FileNotFoundException e) {
         e.printStackTrace();
        }
        
        catch (IOException e) {
            e.printStackTrace();
            
        }
    }
    
    });

    primaryStage.show();



}    

}
英文:

I have a text file with 4 lines of random words, line for line, and I need to be able to read each line and display it to its text field (First line goes into first text field, etc), but it is only reading the last line and displaying it into any text field.

"myfile.txt"
one

two

three

onetwothree

TextField label1Text = new TextField();
TextField label2Text = new TextField();
TextField label3Text = new TextField();


load.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
    @Override
    public void handle(ActionEvent l) {
        
        
        String line = &quot;&quot;; 
        try {
        BufferedReader reader = new BufferedReader(new FileReader(&quot;myfile.txt&quot;));
              
            while ((line = reader.readLine()) != null) {
           
              label1Text.setText(line);
              label2Text.setText(line);
              label3Text.setText(line);
              labelO2Text.setText(line);   
            }
            
        } 

        catch (FileNotFoundException e) {
         e.printStackTrace();
        }
        
        catch (IOException e) {
            e.printStackTrace();
            
        }
    }
    
    });

    primaryStage.show();
    

    
}    

}

答案1

得分: 1

你目前的代码逐行读取,对于每一行,将所有标签的文本设置为该行文本。

相反,你需要逐个处理每个标签,并将其文本设置为文件中的下一行。你可以使用类似以下方式实现:

try (BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"))) {
    List.of(label1Text, label2Text, label3Text, label02Text)
        .forEach(label -> {
            try {
                label.setText(reader.readLine());
            } catch (IOException exc) {
                // 处理异常
            }
        });
}
英文:

Your current code reads each line in turn, and for each line sets the text of all the labels to that line of text.

Instead, you need to take each label in turn, and set its text to the next line from the file. You can do that with something like:

try (BufferedReader reader = new BufferedReader(new FileReader(&quot;myfile.txt&quot;))) {
    List.of(label1Text, label2Text, label3Text, label02Text)
        .forEach(label -&gt; {
             try {
                label.setText(reader.readLine());
             } catch (IOException exc) {
                 // handle exception
             }
        });
} 

答案2

得分: 0

以下是翻译好的部分:

你正在读取一行,然后将该行的内容设置为所有3/4个文本字段的内容(在你的示例中缺少一个)。循环结束后,所有文本字段都设置为文件的最后一行内容。

有多种方法可以实现你想要的效果 - 如果你只有4个条目,以下方法将起作用:

String[] lines = new String[4];
int index = 0;
while ((line = reader.readLine()) != null) {   
    lines[index++] = line;
    if (index == 4) break;
}
label1Text.setText(lines[0]);
label2Text.setText(lines[1]);
label3Text.setText(lines[2]);
label4Text.setText(lines[3]);

如果你在数组中有对文本字段的引用,你也可以这样做:

int index = 0;
while ((line = reader.readLine()) != null) {   
    labels[index++].setText(line);
    if (index == 4) break;
}
英文:

You are reading a single line, then setting the content of that line to all 3/4 TextFields (there is one missing in your example). After the loop finishes, all TextFields are set to the content of the last line of your file.

There is a variety of ways to achieve what you want - if you only ever have 4 entries, the following will work:

 String[] lines = new String[4];
 int index = 0;
 while ((line = reader.readLine()) != null) {   
    lines[index++] = line;
    if (index==4) break;
 }
 label1Text.setText(lines[0]);
 label2Text.setText(lines[1]);
 label3Text.setText(lines[2]);
 label4Text.setText(lines[3]);

If you had references to your TextFields in an array, you could also do

 int index = 0;
 while ((line = reader.readLine()) != null) {   
    labels[index++].setText(line);
    if (index==4) break;
 }

答案3

得分: 0

问题出在你的循环中:

while ((line = reader.readLine()) != null) {
    label1Text.setText(line);
    label2Text.setText(line);
    label3Text.setText(line);
    labelO2Text.setText(line);   
}

基本上,如果我们看一下循环,第一次迭代会将所有标签更改为“One”,循环中的第二次迭代会将所有标签设置为“Two”,然后是“Three”,最后一次迭代会将所有标签都设置为“Four”。

要解决这个问题,你可以添加一个简单的计数器和一些if语句,这样它会告诉你的循环应该做什么。

int counter = 0;
while ((line = reader.readLine()) != null) {
    if(counter == 0)
        label1Text.setText(line);
    if(counter == 1)
        label2Text.setText(line);
    if(counter == 2)
        label3Text.setText(line);
    if(counter == 3)
        labelO2Text.setText(line);
    counter++;                      
}

我确定这不是最优的方法,但如果你想用循环来做,那就这样吧。

英文:

The problem sits in your loop

while ((line = reader.readLine()) != null) {
    label1Text.setText(line);
    label2Text.setText(line);
    label3Text.setText(line);
    labelO2Text.setText(line);   
}

Basically if we look at the loop, first iteration changes all of the labels to the word "One", second iteration in the loop sets all the labels to "Two", than "Three" and last iteration sets all labels as "Four".

To solve the problem you can add a simple counter with some if statements, so it will tell your loop what to do.

int counter = 0;
while ((line = reader.readLine()) != null) {
    if(counter == 0)
        label1Text.setText(line);
    if(counter == 1)
        label2Text.setText(line);
    if(counter == 2)
        label3Text.setText(line);
    if(counter == 3)
        labelO2Text.setText(line);
    counter++;                      
}

I am sure it is not the most optimal way, but if you want to do it with loop, that's it.

huangapple
  • 本文由 发表于 2020年9月1日 00:21:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63674526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定