Before asking this question, I have done my research and tried several things, but nothing seems to work.
Below I included the simplified version of my code.
I have a program that basically moves a chess piece on a chess table. The table is implemented using class JTable. What I am trying to accomplish is to create a couple seconds of delay between each move.
The table is a class that extends JTable. The constructor creates a chess piece on the table.
public Table (int rows, int columns)
{
ChessPiece piece = new ChessPiece();
}
The table has a menu with an option to move the chess piece. This option will move the chess piece forward by calling the method moveForward().
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem item = new JMenuItem("Move Chess Piece");
menu.add(item);
menuBar.add(menu);
item.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
piece.moveForward();
}
});
setJMenuBar(menuBar);
To start the program, I do the following:
Table table = new Table();
javax.swing.SwingUtilities.invokeLater( new Runnable()
{ public void run()
{
table.setVisible(true);
}
} );
So in order to create a couple of seconds of delay, I first tried the following:
public void moveForward()
{
// Sleep for a couple of seconds before moving.
try { Thread.sleep(SLEEP_TIME);}
catch(InterruptedException ex) { Thread.currentThread().interrupt(); }
.....<code to move the chess piece forward>....
}
That causes the entire GUI to freeze when I click on the "Move Chess Piece" option. It is not clear to me why the program to behaves so. If someone can explain in plain English to me, I would appreciate!
I looked around and was advised that I should use java.swing.Timer. So I changed my code to following:
public void moveForward()
{
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt)
{
System.out.println("Hello!");
}
};
javax.swing.Timer t = new javax.swing.Timer(10000, taskPerformer);
t.setRepeats(false);
t.start();
.....<code to move the chess piece forward>....
}
The GUI no longer freezes when I click on the Move Chess Piece option, but it does nothing. There is no 10 seconds delay that I expected.
Please advise what is wrong here!
Thanks in advance.