本文介绍了JTextArea中的append()方法似乎不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们被分配到创建一个简单的编译器的,将采取指令集(包含变量,条件跳转等),并评估他们的功课。这已经做了,但我想我会做我的程序多一点......闪亮,并添加从文本文件中加载指令,只是为了用户的舒适度着想的能力;然而,似乎()方法似乎的追加的JTextArea 并不真的喜欢我,因为它正是这么做没什么。下面是相关的code:

We were assigned to create a simple compiler as a homework that will take set of instructions (containing variables, conditions, jumps, etc.) and evaluate them. That's already done, but I thought I'd make my program little bit more… "shiny", and add the ability to load instructions from a text file, just for the sake of user comfort; however, it seems that the JTextArea's append () method doesn't seem to really like me, as it does exactly nothing. Here's the relevant code:

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 ();
    }
}

(我使用AWT的FileDialog的,而不是Swing的JFileChooser的,因为它只是看起来在Mac上更好,在苹果官方推荐。)

输入变量。有趣的是 - 文件读取部分必须完美无缺的工作,因为我可以看到该文件的内容被写入标准输出感谢到的System.out.println(),而循环内调用。然而,没有出现在的JTextArea ,我已经尝试了所有的现有解决方案,我发现这里的计算器 - 这包括调用重绘( )重新验证()的updateUI()方法。

The input variable used in this code points to the JTextArea instance. The funny thing is – the file reading part must be working flawlessly, as I can see the file content being written to the standard output thanks to the System.out.println () call within the while loop. However, nothing appears in the JTextArea, and I've tried all the existing solutions I've found here on StackOverflow – that includes calling the repaint (), revalidate () and updateUI () methods.

我在想什么?非常感谢所有的答案!

What am I missing? Thanks very much for any answer!

推荐答案

在code可能是对事件调用处理循环,在那里你可以不用图纸。
人们通常会使用

The code probably is called on the event handling loop, where you cannot have drawing.One would normally use

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

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

不幸的是,一些需要照顾的地方放置invokeLatere(如循环)。更好地利用@ AndrewThompson的解决方案。

Unfortunately it takes some care where to place the invokeLatere (as looping). Better use @AndrewThompson's solution.

这篇关于JTextArea中的append()方法似乎不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 13:12