ArpitM
ArpitM

Reputation: 3

Only the last call to a TextField updates it

I want to display program flow to the user in form of comments in a JTextField. Only the last message ("complete") is shown. How can I make each message appear when I call setText()?

private class CalculateButtonHandler implements ActionListener {
    public void actionPerformed(ActionEvent e) {            
        String keyValue = keywordTF.getText();
        currentTF.setText("calling 1");
        methodCall1();
        currentTF.setText("calling 2");
        methodCall2();
        currentTF.setText("calling 3");
        methodCall3();
        currentTF.setText("complete");
    }
}

Upvotes: 0

Views: 123

Answers (2)

Robin
Robin

Reputation: 36601

The reason is that the EDT has no time to repaint the text field since your methodCall* method is running on the EDT.

If you want to show progress of a heavy task you should perform the heavy work on a worker thread and update the UI on the EDT. Typically this is achieved by using a SwingWorker or using SwingUtilities#invokeLater from the worker thread.

The 'Concurrency in Swing' tutorial contains more information

Upvotes: 2

CodeBlind
CodeBlind

Reputation: 4569

Try:

String keyValue = keywordTF.getText();

currentTF.setText("calling 1");
methodCall1();
currentTF.setText(currentTF.getText()+"\ncalling 2");
methodCall2();
currentTF.setText(currentTF.getText()+"\ncalling 3");
methodCall3();
currentTF.setText(currentTF.getText()+"\ncomplete");

Not terribly efficient, but it will get the job done.

Also

It'd be a lot better to use a JTextArea. JTextField is meant primarily for displaying one line of text, but it sounds like you want to keep more of a log... perhaps? If you still want to use a JTextField, then replace the "\n" characters in the calls to setText() with some other appropriate delimiter.

Upvotes: 0

Related Questions