Swing: cannot get JButton to update - repaint () is not working

This is my first time using Swing to create a simple graphical interface. It consists of a JFrame , on which I placed one JButton , which when clicked calls another code that takes approx. 3 seconds to return.

Just before calling this code, in actionPerformed() , I want to update the text on the button to tell the user that processing is happening. My problem is that the text on the button is not updated until the 3 second call returns. I want the updated text to be present during the conversation, after which I will change it later.

The repaint() call in JButton does nothing and calls it on the JFrame as a result of " Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException " when I click the button.

+7
java swing swingworker repaint
source share
2 answers

What happens is that the 3 second code is executed in the GUI thread, so the button cannot be updated until it is executed.

To solve this problem, run SwingWorker to perform a lengthy operation; then you can still do something in the GUI while you wait for it.

Here are a couple of subject tutorials and the SwingWorker Javadocs mentioned above also have code.

Code example

 public void actionPerformed(ActionEvent e) { SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override public Void doInBackground() { // Call complicated code here return null; // If you want to return something other than null, change // the generic type to something other than Void. // This method return value will be available via get() once the // operation has completed. } @Override protected void done() { // get() would be available here if you want to use it myButton.setText("Done working"); } }; myButton.setText("Working..."); worker.execute(); } 
+15
source share

The problem is that your long-term task is blocking the thread that the GUI usually draws.

The usual way is to drop a longer work task into another thread.

This can be done quite easily using SwingWorker .

This question may also provide some useful information.

+10
source share

All Articles