I'm trying to add a JLabel to a JComponent (which is already on a JPanel), then making it so that I can click and drag the JLabel to reposition it somewhere different.
At the moment the JLabel does appear but when I click and drag it, it moves the whole JComponent instead of just the JLabel on its own.
Here is an example of the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.*;
public class Test extends JComponent implements ActionListener {
int dragX, dragY;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.drawRect(0, 0, 300, 300);
MouseListener ml = new MouseListener() {
public void mousePressed(MouseEvent e) {
dragX = e.getX();
dragY = e.getY();
}
};
MouseMotionAdapter mma = new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e){
setLocation(e.getX() - dragX + getLocation().x,
e.getY() - dragY + getLocation().y);
}
};
BufferedImage image;
try {
image = ImageIO.read(new File("image.png"));
ImageIcon i = new ImageIcon(image);
JLabel label = new JLabel(i);
label.setBounds(30, 30, 60, 19);
label.addMouseListener(ml);
label.addMouseMotionListener(mma);
add(label);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900, 650);
frame.setVisible(true);
frame.setResizable(false);
Test t = new Test();
frame.getContentPane().add(t);
}
}
I feel like it has something to do with the setLocation()
line in the MouseMotionAdapter()
block, but I'm not entirely sure.
Thanks in advance!