views:

19

answers:

2

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

+1  A: 

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.

Bill K
+1  A: 

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.

Justin Ardini
Many thanks for the reply I'm trying it right now and it seems to be the best choice...I have one small question....why does this give me an error saying "missing return value" on the doInBackground function if it's Void (void doesn't seem to work as it must return an object) SwingWorker myworker=new SwingWorker<Void,Void>(){ @Override protected Void doInBackground() { System.out.println("ola"); } };
out_sider