阅读量:1
要实现鼠标拖动画矩形,可以使用Java的Swing库来完成。下面是一个简单的示例代码:
import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class DraggableRectangle extends JFrame { private int initialX, initialY; private int currentX, currentY; private Rectangle rectangle; public DraggableRectangle() { setTitle("Draggable Rectangle"); setSize(400, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 创建矩形并设置初始位置和大小 rectangle = new Rectangle(100, 100, 100, 100); // 添加鼠标事件监听器 addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { // 记录鼠标按下时的初始位置 initialX = e.getX(); initialY = e.getY(); } }); addMouseMotionListener(new MouseAdapter() { @Override public void mouseDragged(MouseEvent e) { // 计算鼠标拖动后的位置 currentX = e.getX(); currentY = e.getY(); // 计算矩形的偏移量 int offsetX = currentX - initialX; int offsetY = currentY - initialY; // 更新矩形的位置 rectangle.setLocation(rectangle.x + offsetX, rectangle.y + offsetY); // 重绘窗口 repaint(); // 更新初始位置 initialX = currentX; initialY = currentY; } }); } @Override public void paint(Graphics g) { super.paint(g); // 绘制矩形 g.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DraggableRectangle draggableRectangle = new DraggableRectangle(); draggableRectangle.setVisible(true); }); } }
运行以上代码,将会显示一个可拖动的矩形窗口。当鼠标按下并拖动时,矩形会跟随鼠标的移动而移动。