要實現鼠標拖動畫矩形,可以使用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);
});
}
}
運行以上代碼,將會顯示一個可拖動的矩形窗口。當鼠標按下并拖動時,矩形會跟隨鼠標的移動而移動。