我想画一幅画 然后定义相对坐标 当相对坐标移动时 那副画会整体移动、、、该怎么实现、、、
------解决方案--------------------
package com.tur.demo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
public class Hello extends JPanel {
private Rectangle2D imageBoundingRect; // 图像的矩形区
private Point mousePressedPos; // 鼠标按下的位置
private boolean imageSelected = false; // 图像被选中
private Image image;
public Hello() {
imageBoundingRect = new Rectangle2D.Double(10, 10, 150, 150);
mousePressedPos = new Point();
image = new ImageIcon("/Users/Biao/Desktop/x.png").getImage();
MyMouseAdapter ma = new MyMouseAdapter();
addMouseListener(ma);
addMouseMotionListener(ma);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// 在此矩形框内绘制图像
g2d.drawImage(image,
(int) imageBoundingRect.getX(),
(int) imageBoundingRect.getY(),
(int) imageBoundingRect.getWidth(),
(int) imageBoundingRect.getHeight(),
this);
if (imageSelected) {
// 图像被选中时高亮边框
g2d.setColor(Color.RED);
g2d.draw(imageBoundingRect);
}
}
private static void createGuiAndShow() {