JButton ActionListener - GUI updates only after JButton is clicked

梦想与她 提交于 2019-11-26 06:07:28

问题


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.


回答1:


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:

  • Override doInBackground(), and put any long operations inside this method so that it will be run on a separate thread rather than the EDT.

  • For any GUI creation or changing states of GUI components within doInBackground(), use publish(V... chunks) to send data to process(List<V> chunks). You need to override process(List<V> chunks). Also note that process(List<V> chunks) is executed on EDT.

  • After doInBackground() returns, done() executes on EDT and you can override it to use it for any GUI updates. You can also retrieve the value returned from doInBackground() by using get().

  • Note that SwingWorker<T,V> is generic, and you need to specify the types. T is the type of object returned from doInBackground() and get(), while V is the type of elements you passed to process(List<V> chunks) via publish(V... chunks).

  • execute() method starts the swing worker by invoking doInBackground() first.

For more on this, please read Concurrency in Swing.



来源:https://stackoverflow.com/questions/11545288/jbutton-actionlistener-gui-updates-only-after-jbutton-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!