JButton ActionListener - GUI updates only after JButton is clicked
Asked Answered
M

1

5

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.

Misguidance answered 18/7, 2012 at 15:48 Comment(3)
Do you mean that you have several changes to labels and textareas and you want them to happen one-by-one with the user seeing each step?Yearbook
For easier reading, please stick to spelling rules (first letter in a sentence should be capitalized :-)Smack
Don't use Thread.sleep(...) like calls inside your GUI Code. Instead use javax.swing.TImer for this purpose, might be you not updating your stuff on the EDT - Event Dispatch Thread, this might help you in that :-)Thearchy
E
13

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.

Electrophorus answered 18/7, 2012 at 16:37 Comment(1)
Agree, 1+. I've also edited it to add a Concurrency in Swing tutorial link.Natashianatassia

© 2022 - 2024 — McMap. All rights reserved.