Heaney
Heaney

Reputation: 53

How to make button changes repaint -during- method, not after?

Inside the actionPerformed method of a jButton, I have the following code:

btnLogin.setText("Logging In...");
btnLogin.setPreferredSize(new Dimension(110, 29));
btnLogin.setEnabled(false);

//more stuff here, irrelevant to this

This works, however it only takes visual effect (is repainted) once the method is complete.

If in the //more stuff here area I have code that takes a long time to complete, the effects of the btnLogin changes do not take effect until that code is complete.

I have tried typing:

this.revalidate();
this.repaint(); 

Directly after the first 3 lines, and multiple other solutions, to try to force the damn thing to repaint DURING the method, but no matter what, it only happens at the end!

Another thing I've noticed is that if I call a JOptionPane in the middle of the method, the frame WILL repaint (in the background), so that's interesting.

What is is that's automatically happening in the end of the method that I need to call to make it happen during the method?

Thanks in advance!

Upvotes: 1

Views: 47

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You're blocking the Swing event thread with the long-running code, and this prevents Swing from drawing the text changes. The solution:

  • Do the long-running code in a background thread such as in a SwingWorker's doInBackground method.
  • But make sure to make most all Swing calls on the Swing event thread.
  • Read the Concurrency in Swing tutorial to learn the details on the Swing event thread and threading issues.

Upvotes: 2

Related Questions