Search code examples
javaswinguser-interfacejbuttonswingworker

JButton ActionListener - GUI updates only after JButton is clicked


I'm having a problem with my JButton ActionListener. I have a doTheCleaning() method defined in another class which when called makes series of changes to my GUI.

public void doTheCleaning(){
    //change image icon
    //had thread.sleep here
    //insert to text area
    //had thread.sleep here
    //etc
}

Then in another class, I instantiated the class containing my doTheCleaning() method and had my ActionListener written with my actionperformed() method for my jbutton written like this:

public void actionPerformed(ActionEvent e){
   //some code
   //newClass.doTheCleaning();
}

I know how to do the rest like addActionListener() and stuff so no need to question about that. My concern is that all the changes in my GUI that is performed when doTheCleaning() method is called applies only after the button is clicked. When this happens, the succession between the changes that happened in my labels and textarea were not shown. The code works fine if i called it directly in my tester class but calling it inside the actionperformed method shows only the final state of my GUI. I need to show which element changed first, then what's next, and so on.

How could I achieve it when I need these changes to occur only when I click the JButton?

**I'm not so good with doing GUI in java yet. iIhope you guys understood my point without me giving my code. but I could if necessary. Thanks.


Solution

  • Do not perform any intensive operations within EDT, otherwise the GUI will be unresponsive and you might not see the GUI updates. Best choice you can use is SwingWorker:

    For more on this, please read Concurrency in Swing.