This is a followup question from my previous question. I am trying to solve the issue in the previous question. link
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.
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 moves the mouse cursor to a specific button coordinate on the other 3x3 grid as the user drags the pieces from the original 3x3 grid.
Edited : Edited code is marked. Flex seems to have a method which can detect the object which is under the cursor, does java have it ? Link ^ getSource() solves the above issue.
However, when I tried system.out.println
to see when does the button run the getName()
, it appears that it doesn't run when I drag the pieces to the button; to activate getName()
, I must further hover over the button after dragging the image pieces to the button =/ .
private int mouseX,mouseY;
private JButton[] button = new JButton[9];
private JButton[] userarea = new JButton[9];
// 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);
}
// create 9 buttons for the user to place the puzzle pieces to
for(int b=0; b<9; b++){
userarea[b] = new JButton();
id2 += Integer.toString(++cc2);
// setName for each button (as unique id)
userarea[b].setName(id2);
TransferHandler transfer1 = new TransferHandler("icon");
userarea[b].setTransferHandler(transfer1);
//<--- EDITED CODE ------>
ChangeListener clistener = new ChangeListener(){
public void stateChanged(ChangeEvent ce) {
JButton source = (JButton)ce.getSource();
ButtonModel mod = source.getModel();
if (mod.isRollover()){
System.out.println(source.getName());
}
else{
}
}
};
//<--- EDITED CODE ------>
}
public void nameOfDestButton() {
// not sure how to do this
if(mouseCoordinate == getBounds of one of the buttons){
userarea[appropriate button number].getName();
}
}
public void mouseMoved(MouseEvent m){
mouseX=m.getX();
mouseY=m.getY();
nameOfDestButton();
// not sure how to do this. Obtaining a return value of getName
// in the nameOfDestButton() method ?
if (m.getComponent().getName().equals(nameOfDestButton) {
}
else{
JOptionPane.showMessageDialog(null,"Wrong! Try Again.");
}
}