JTextArea's append () method doesn't seem to work

喜欢而已 提交于 2020-01-14 13:09:38

问题


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

(I'm using Awt's FileDialog instead of Swing's JFileChooser because it simply looks better on Mac, as seen in Apple's official recommendation.)

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!


回答1:


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

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



来源:https://stackoverflow.com/questions/12996842/jtextareas-append-method-doesnt-seem-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!