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

时间:2019-05-12 15:09:38

标签: java swing jtextarea

我想将内容从文本文件传输到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);
}

1 个答案:

答案 0 :(得分:0)

此代码中有两个重要问题:

  • 您正在创建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();
    }
相关问题