I am coding an image puzzle game and one part of the code is to compare the pieces the user has selected to the pieces of the correct image to check if it is correct.
Each image piece is already added to a JButton as an ImageIcon.
An identifier is required to differentiate each image piece apart and also for comparision.
I am setting a setName() for each JButton created as the identifier.
The comparison starts when the user releases the mouse after he drags the puzzle pieces from the original 3x3 grid where the shuffled pieces are to the other 3x grid for matching.
I am trying to compare the names of the source image with the names of the destination buttons of the grid which the user is trying to place the pieces to.
x.getName() doesn't work as x is an array. So I tried to implement setAction for each button to getName, but I couldn't quite understand how to use it =/
Any help is appreciated.
private JButton[] button = new JButton[9];
private JButton[] x = 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(image));
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++){
x[b] = new JButton();
id2 += Integer.toString(++cc2);
x[b].setName(id2);
// for each button, setAction to getName
x[0].setAction(new ButtonAction(x.getName())); // error here
}
// 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 mouseMoved(MouseEvent m){
if (m.getComponent().getName().equals(x.getName())) { // error here
}
else{
JOptionPane.showMessageDialog(null,"Wrong! Try Again.");
}
}
}