Skip to content

Instantly share code, notes, and snippets.

@Ayouuuu
Created August 22, 2023 03:22
Show Gist options
  • Save Ayouuuu/be528ca793ff9fb912e465b1b5ffba37 to your computer and use it in GitHub Desktop.
Save Ayouuuu/be528ca793ff9fb912e465b1b5ffba37 to your computer and use it in GitHub Desktop.
坐标1围绕坐标2做圆周运动
package com.ayou;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class CircularMotionWithMouse extends JPanel {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int RADIUS = 100;
private int centerX, centerY;
private double angle = 0;
public CircularMotionWithMouse() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
// 更新坐标2的位置为鼠标指针位置
centerX = e.getX();
centerY = e.getY();
repaint();
}
});
Timer timer = new Timer(20, e -> {
// 更新角度以模拟圆周运动
angle += 0.05;
repaint();
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int pointX = (int) (centerX + RADIUS * Math.cos(angle));
int pointY = (int) (centerY + RADIUS * Math.sin(angle));
g.setColor(Color.BLUE);
g.fillOval(pointX - 5, pointY - 5, 10, 10); // 绘制运动的点
g.setColor(Color.RED);
g.fillOval(centerX - 5, centerY - 5, 10, 10); // 绘制坐标2
}
public static void main(String[] args) {
JFrame frame = new JFrame("Circular Motion With Mouse");
CircularMotionWithMouse circularMotion = new CircularMotionWithMouse();
frame.add(circularMotion);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment