JTextArea的append()方法似乎不起作用

Cel*_*ane 4 java file-io swing append jtextarea

我们被分配创建一个简单的编译器作为家庭作业,将采取一组指令(包含变量,条件,跳转等)并评估它们.这已经完成了,但我想我会让我的程序更多......"闪亮",并添加从文本文件加载指令的能力,只是为了用户的舒适; 但是,似乎JTextAreaappend ()方法似乎并不真的喜欢我,因为它不会完全没有.这是相关的代码:

BufferedReader bufferedReader;
File file;
FileDialog fileDialog = new FileDialog (new Frame (), "Open File", FileDialog.LOAD);
String line;

fileDialog.setVisible (true);

if (fileDialog.getFile () != null) {
    file = new File (fileDialog.getDirectory () + fileDialog.getFile ());
    input.setText (""); // delete old first

    try {
        bufferedReader = new BufferedReader (new FileReader (file));
        line = bufferedReader.readLine ();

        while (line != null) {
            input.append (line);
            System.out.println (line);
            line = bufferedReader.readLine ();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace ();
    }
}
Run Code Online (Sandbox Code Playgroud)

(我正在使用Awt的FileDialog而不是Swing的JFileChooser,因为它在Mac上看起来更好,正如Apple的官方推荐中所见.)

input此代码中使用的变量指向JTextArea实例.有趣的是 - 文件读取部分必须完美地工作,因为我可以看到文件内容被写入标准输出,这要归功于循环System.out.println ()内的调用while.然而,没有出现在JTextArea,我已经尝试了所有现有的解决方案,我发现这里在计算器上-包括调用repaint (),revalidate ()updateUI ()方法.

我错过了什么?非常感谢您的回答!

Joo*_*gen 5

代码可能在事件处理循环中调用,您无法绘制.人们通常会使用

final String line = bufferedReader.relineadLine();
// final+local var so usable in Runnable.

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        input.append(line + "\n");
    }
} 
Run Code Online (Sandbox Code Playgroud)

不幸的是,它需要注意放置invokeLatere的位置(作为循环).更好地使用@ AndrewThompson的解决方案.