У меня есть JPanel внутри JFrame, и в JPanel есть несколько BufferedImages. Перетаскивание BufferedImage в JPanel
Теперь мой вопрос: как я могу перемещать BufferedImages внутри JPanel? Подробнее Как добавить MouseEventhandler к буферизованным изображениям ?. Хотя я могу перетащить JPanel из кода ниже, но не могу понять, как перетаскивать буферные изображения внутри JPanel. Спасибо за помощь.
У меня есть три класса, как этот
MainWindow.Java
public class MainWindow extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
}
}
});
}
public MainWindow() {
JFrame frame = new JFrame();
.... // Other code of JFrame
JPanel panel_3 = new JPanel();
.... // other code of JPanel
frame.getContentPane().add(panel_3);
panel_3.setLayout(new BorderLayout(0, 0));
Drawing drawingObj = new Drawing();
panel_3.removeAll();
panel_3.add(drawingObj);
drawingObj .revalidate();
drawingObj .repaint();
BasicDragging drag= new BasicDragging();
panel_3.addMouseListener(drag);
panel_3.addMouseMotionListener(drag);
}
}
Drawing.java
public class Drawing extends JPanel {
private BufferedImage Image1 ;
private BufferedImage Image2;
private BufferedImage Image3;
public Drawing() {
try {
Image1 = ImageIO.read(new File("path of file"));
Image2 = ImageIO.read(new File("path of file"));
Image3 = ImageIO.read(new File("path of file"));
}
catch (IOException ex) {
// handle exception...
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(Image1 , 150, 10, null);
g.drawImage(Image2 , 150, 70,null);
// Other code of drawing images
}
}
}
BasicDragging.java
public class BasicDragging extends MouseInputAdapter{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me)
{
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
}