gpt4 book ai didi

java - 如何读取File并将内容写入JTextArea?

转载 作者:行者123 更新时间:2023-12-02 05:45:23 24 4
gpt4 key购买 nike

我想将文本文件中的内容传输到JTextarea。我想我的代码只需要小的调整,但即使是通过研究。我无法找出问题所在。到目前为止,它只是显示一个空的 JFrame 而不是文件的文本。

this.setSize(this.width, this.height);
this.setVisible(true);
this.jScrollPane = new JScrollPane(this.jTextArea);
this.jPanel = new JPanel();
this.jPanel.setOpaque(true);
this.jTextArea.setVisible(true);

try {
this.jTextArea = new JTextArea();
this.jTextArea.read(new InputStreamReader(
getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")),
null);

} // catch

this.add(this.jScrollPane);

以及用法:

public static void main(String[] args) {
new TextFrame(new File("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name"), 500, 500);
}

最佳答案

这段代码中有两个重要的问题:

  • 您正在创建 jScrollPane this.jScrollPane = new JScrollPane(this.jTextArea);,然后再使用 jTextArea 读取文件内容
  • 该方法不起作用 read(new InputStreamReader(
    getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")), null);
    使用以下示例中的那个。

你必须捕获异常才能解决问题

  public class TextAreaDemo extends JFrame {

private JScrollPane jScrollPane;
private JTextArea jTextArea ;
private static final String FILE_PATH="/Users/user/IdeaProjects/StackOverflowIssues/file.txt";

public TextAreaDemo() {

try {
jTextArea = new JTextArea(24, 31);

jTextArea.read(new BufferedReader(new FileReader(FILE_PATH)), null);

} catch (Exception e){

e.printStackTrace();
}

jScrollPane = new JScrollPane(this.jTextArea);
this.add(this.jScrollPane);
this.setVisible(true);
this.setSize(400, 200);
}
public static void main(String[] args) {
TextAreaDemo textAreaDemo = new TextAreaDemo();
}

关于java - 如何读取File并将内容写入JTextArea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56100557/

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