Could you achieve this with Component
s, yes, but you'd need to translate between the component and it's parent as well as take over the responsibility of the layout manager.
Generally speaking, it would be easier to "cheat" and simply draw the image at a different offset within the component itself, for example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DraggableImage {
public static void main(String[] args) {
new DraggableImage();
}
public DraggableImage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImagePane extends JPanel {
private BufferedImage img;
private Point offset = new Point(0, 0);
public ImagePane() {
try {
img = ImageIO.read(new File("/Users/swhitehead/Dropbox/MegaTokyo/MT015.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
MouseAdapter ma = new MouseAdapter() {
private Point startPoint;
@Override
public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
startPoint.x -= offset.x;
startPoint.y -= offset.y;
}
@Override
public void mouseReleased(MouseEvent e) {
startPoint = null;
}
@Override
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
int x = p.x - startPoint.x;
int y = p.y - startPoint.x;
offset = new Point(x, y);
repaint();
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
Graphics2D g2d = (Graphics2D) g.create();
if (offset == null) {
offset = new Point(0, 0);
}
g2d.drawImage(img, offset.x, offset.y, this);
g2d.dispose();
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…