Reputation:
I have a JLabel (with an icon) and I would like to translate this JLabel when the JLabel is clicked. I have added a mouseListener to the JLabel however I didn't come up with anything on how I can execute a translation from coordinates (x, y) to cordinates (x', y')
class MyMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e){
final JLabel label = (JLabel) e.getSource();
System.out.println("Player hit label -> " + label.getName() );
// Code for translating JLabel
}
}
Upvotes: 1
Views: 372
Reputation: 35096
As far as translating (ie moving) your JLabel:
First, you must make sure that the layout manager of its parent is set to null, or uses a customized layoutmanager that can be configured to do your translation.
Once you have that in place, it's a simple matter:
public void mouseClicked(MouseEvent ae) {
JLabel src = (JLabel) ae.getSource();
src.setLocation(src.getLocation().x + delta_x, src.getLocation().y + delta_y);
src.getParent().repaint();
}
Upvotes: 2