我确实不知道您想在评论中确切知道什么,尽管对上述答案+1,但在我看来,这才是真正的原因。看一下这个示例程序,只需将您的调用添加到中的
move(...)方法中
timerAction,似乎可以为您工作。在这里试试这段代码:
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class GridExample{ private static final int SIZE = 36; private JButton[] buttons; private int presentPos; private int desiredPos; private Timer timer; private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon"); private ActionListener timerAction = new ActionListener() { public void actionPerformed(ActionEvent ae) { buttons[presentPos].setIcon(null); if (desiredPos < presentPos) { presentPos--; buttons[presentPos].setIcon(infoIcon); } else if (desiredPos > presentPos) { presentPos++; buttons[presentPos].setIcon(infoIcon); } else if (desiredPos == presentPos) { timer.stop(); buttons[presentPos].setIcon(infoIcon); } } }; public GridExample() { buttons = new JButton[SIZE]; presentPos = 0; desiredPos = 0; } private void createAndDisplayGUI() { Jframe frame = new Jframe("Grid Game"); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); JPanel contentPane = new JPanel(); contentPane.setLayout(new GridLayout(6, 6, 5, 5)); for (int i = 0; i < SIZE; i++) { final int counter = i; buttons[i] = new JButton(); buttons[i].setActionCommand("" + i); buttons[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { desiredPos = Integer.parseInt( (String) buttons[counter].getActionCommand()); timer.start(); } }); contentPane.add(buttons[i]); } buttons[presentPos].setIcon(infoIcon); frame.setContentPane(contentPane); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); timer = new Timer(1000, timerAction); } public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new GridExample().createAndDisplayGUI(); } }); }}


