First, I would recommended using a layout instead of setLayout(null) and setBounds(). Secondly, seperate the ImageIcon from the JLabel. Finally, set the JLabel and the ImageIcon as fields instead of a local variable.
You need to add a MouseListener and a MouseMotionListener.
label.addMouseMotionListener(new MouseAdapter()
{
public void mouseMoved(MouseEvent arg0)
{
if(clicked)
{
label.x++
label.y++
label.repaint();
}
}
});
label.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent arg0)
{
clicked = !clicked;
}
});
(Sorry for being wordy beforehand)
This causes the image of the label to appear where the label is, and when you your mouse over it it will move diagonal southeast. I created a new label class, where I override paintComponent and added in there a paint image icon method, where the x and y are variables. The idea will be to calculate a center point on your label, then move the x position of the image west if going west of that point (x--), south if going south(y--), ect. This would only move your image inside the label. If your mouse if outside of the label, the moving would stop. If parts of the image are outside of the label, then that part will not be shown. I would override paint compoent in your label class and move the image over, then set the icon for each movement.
public class Label1 extends JLabel
{
public int x;
public int y;
ImageIcon imageIcon = new ImageIcon("path");
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//No setLocation(x, y) method exists for an image icon or an image. You are on your own on this
imageIcon.setLocation(x, y);
label.setIcon(imageIcon);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…