我正在编写一个图像拼图游戏,代码的一部分是将用户选择的片段与正确图像的片段进行比较。
每个图像片段都已作为 ImageIcon 添加到 JButton。
需要一个标识符来区分每个图像片段并进行比较。
我正在为每个创建为标识符的 JButton 设置一个 setName() 。
当用户将拼图块从原始 3x3 网格拖动到另一个 3x 网格进行匹配后,比较开始。
我在从比较中删除错误时遇到问题if
陈述。
我从这个SO线程中得到了比较的想法 -link https://stackoverflow.com/questions/227143/java-what-is-java-awt-component-getname-and-setname-used-for%22Link%22
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.");
}
}
}
In your mouseReleased
event m.getButton()
返回被单击的鼠标按钮。你会想做一些类似这样的事情来让你们更接近:
if (m.getComponent().getName().equals(waa.getName())) {
m.getComponent()
返回Component
对象(你的JButton
) 事件被触发。从那里您可以与getName
您正在使用的方法。
还有一个额外的问题是你的waa
变量是一个数组。我不确定您想要如何比较它们,是否运行数组并确保索引和名称匹配,但这是您需要研究的另一个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)