我正在编码图像益智游戏,代码的一部分是比较用户选择的部分片段的正确图像。通过setName()比较组件。
每个图像片段已作为ImageIcon添加到JButton中。
需要一个标识符来区分每个图像块并进行比较。
我为每个JButton创建一个setName()作为标识符。
比较在用户从原始3x3网格中拖拽拼图后释放鼠标时开始,在这个网格中将混洗的部分放到其他3x网格进行匹配。
我有问题,从比较if
声明中删除错误。
我从这个SO线程比较主意 - link
private JButton[] button = new JButton[9];
private JButton[] waa = new JButton[9];
private String id;
private int cc;
private String id2;
private int cc2;
// setName for each of the 9 buttons in the original 3x3 grid being created
// which stores the shuffled puzzle pieces
for(int a=0; a<9; a++){
button[a] = new JButton(new ImageIcon());
id += Integer.toString(++cc);
button[a].setName(id);
}
// setName for each of the 9 buttons in the other 3x3 grid
// where the images will be dragged to by the user
for(int b=0; b<9; b++){
waa[b] = new JButton();
id2 += Integer.toString(++cc2);
waa[b].setName(id2);
}
// check if puzzle pieces are matched in the correct place
// compare name of original 'button' array button with the name of 'waa' array buttons
button[a].addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent m){
if(m.getbutton().getName().equals (waa.getName())){
}
else{
JOptionPane.showMessageDialog(null,"Wrong! Try Again.");
}
}
}
如果您不关心是否鼠标事件发生在按钮上,MouseEvent包含一个getComponent方法,该方法应允许放弃演员(至少您确定您想要)。就我个人而言,我也正在检查以确保getName没有返回空值 – MadProgrammer
其实,当我想到它时,为什么我们在按钮上使用鼠标监听器? – MadProgrammer
关于'getComponent'的好处是,我更新了代码。鼠标监听器也是不必要的,它可以通过'addActionListener'完成。在上面的代码中显然有一些问题,但希望这会让OP开始朝着正确的方向发展。 –