所以我收到了一个用 Java 制作 8 block 拼图的作业,我选择使用 JButtons 来制作图 block (不知道这是否可能)。我已经让按钮在启动时以随机顺序出现,但我不知道如何使图 block 在单击它们时能够移动。所以我想知道是否有人可以指出我正确的方向?我得出的结论是,我需要使用 Actionlistners
,并且看到一位老用户在这里获得了在每个按钮上执行 Actionlistners
的提示,但我不知道该做什么令状,我要把它放在另一个类(class)吗?
非常感谢任何帮助!
目前的产品:
最佳答案
为了更容易,您可以添加第九个按钮,该按钮是透明且不可点击的。每个but都应该有他的id,这也能告诉他他的位置。
11 12 13
21 22 22
31 32 33
因此,对于每个按钮,您已经分配了他的随机数。现在就像您使用 Action 监听器来检测单击了哪个按钮一样。当单击时,您检查相邻的按钮是否透明。如果透明,您将交换这些值,一个将变得可见,另一个将透明且不可点击。
要获取相邻按钮,您可以使用 + 和 - 操作。
int leftNeighbour = id - 1;
int rightNeighbour = id + 1;
int topNeighbour = id - 10;
int bottomtNeighbour = id + 10;
我假设所有按钮都保存在一个数组中,所以你只需像这样:
for(Button tempButton : Buttons)
{
if(leftNeighbour > 0 && leftNeighbour == tempButton.id) //we check first if button id is OK, then we compere it with tempButtons id
{
int tempButtonValue = tempButton.value;
tempButton.value = currentButton.value;
currentButton.value = tempButtonValue ;
makeButtonTransparent(tempButton);
break; //we found over neighbor so we can stop for loop
}
//then you check conditions for other neighbor id's. Butt first condition is allays different
}
我希望我没有把它弄得太复杂,但这是我在几分钟内想到的想法,当时我正在思考如何用按钮来制作它。可能有一些更好的方法来为按钮设置 ID,并检查它们是否是邻居。
关于java - 如何使 JButton 移动到空图 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34746126/