好吧,我正在通过创建 java 应用程序进行速成类(class),并且在执行操作时遇到问题。该程序是 15 个拼图,在该游戏中,您一次滑动一 block 并尝试按顺序获得所有数字,因此我允许使用“自动”模式选项,一旦用户单击,该选项就会为用户解决棋盘问题。因此,我的代码从文本文件中读取解决方案,该文件工作正常,只是当我单击自动按钮时,没有任何“方 block ”(JButtons)移动。所以我不确定我是否完全不理解这个 Action 甚至过程。这是我的代码,如果需要,我可以提供更多代码。
if (e.getSource() == ctrButtons[0]) {
System.out.println("Auto Mode started\n");
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("move_list.txt")));
int count = 0;
while (s.hasNext()) {
//Cycle through to move in move_list
if (count != 18) {
s.next();
count+=1;
}
else {
int cur_move = Integer.parseInt(s.next());
count = 0;
/*Use cur_move to move blank space accordingly
*UP------------3
*LEFT----------2
*RIGHT---------1
*DOWN----------0
*/
int zero_index = -1;
for (int j=0; j<jbnButtons.length; j++) {
if (Integer.parseInt(jbnButtons[j].getText()) == 0) {
zero_index = j;
break;
}
}
Point zero = jbnButtons[zero_index].getLocation();
//Check if move is up
if (cur_move == 3) {
Point next = jbnButtons[zero_index-4].getLocation();
jbnButtons[zero_index].setLocation(next);
jbnButtons[zero_index-4].setLocation(zero);
}
//Check if move is left
else if (cur_move == 2) {
Point next = jbnButtons[zero_index-1].getLocation();
jbnButtons[zero_index].setLocation(next);
jbnButtons[zero_index-1].setLocation(zero);
}
//Check if move is right
else if (cur_move == 1) {
Point next = jbnButtons[zero_index+1].getLocation();
jbnButtons[zero_index].setLocation(next);
jbnButtons[zero_index+1].setLocation(zero);
}
//Check if move is down
else {
System.out.println("Current move = 0");
Point next = jbnButtons[zero_index+4].getLocation();
jbnButtons[zero_index].setLocation(next);
jbnButtons[zero_index+4].setLocation(zero);
}
}
}
}
因此,当我单击“自动”按钮时,我的代码就会执行,并且我将输出打印到屏幕上,以查看它是否在循环执行代码,只是每次循环时没有任何按钮移动。有什么想法吗??
最佳答案
您的代码正在事件调度线程上执行。在代码执行完成之前,GUI 无法重新绘制自身,因此您不会看到中间步骤,只能看到每个组件的最终位置。
阅读 Concurrency 上的 Swing 教程中的部分以获得更完整的解释。
也许您应该使用 Swing Timer(教程也有相关部分)。每次计时器触发时,您都会执行下一步操作。
关于java - Java中的ActionEvent移动多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6419180/