简体   繁体   中英

JButtons don't imediatly change on mouse event

I'm using the java swing library to develop a board game called DAO.

The problem is that after the human player makes its move, by clicking on the JButton with the piece image that he wants to play, I call the computer AI routine but inside the mouse event function. By doing this only when the function returns, the computer ends its turn, do the JButtons refresh their Images (setIcon comes in).

I'd like to know how can I force the JButtons to change their image at the moment they are clicked and not only when the mouse event function ends (as I need to handle data inside it).

I've tried all of this

                    myButtons[i][j].setIcon(xIcon);
                    myButtons[i][j].revalidate();
                    myButtons[i][j].repaint();
                    myButtons[i][j].validate();

None worked.

Thx in advance

There is a single thread used for all Swing activity.

Here's the process.

  • One event appears on the event queue
  • it is pulled from the queue and executed by The AWT Thread
  • Any new events created while this is executing are placed on the queue to be held until the currently running AWT event returns.
  • The event executing returns and the next event on the queue is dequeued and executed.

This means that if you need to do anything that takes more than, say 1/100 of a second or so, you shouldn't do it any thread started from a swing event. Instead, spawn your own thread and return the swing thread to the system so the GUI can be updated.

Now, your thread MUST NOT update any GUI objects! If you need to update a GUI object, use invokeLater to place your code back on the AWT thread.

New Java programmers not conforming to this rule and executing tasks on the AWT thread is almost certainly the biggest reason people think Java is slow.

You may want to try putting the action performed upon clicking the JButton into a Swing worker. This will allow the task to go on in the background, while the user can still click other buttons, etc.

See http://java.sun.com/docs/books/tutorial/uiswing/concurrency/simple.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM