Creating an animation with six rotating circles in Java can be a fun challenge! Here's an example using Java Swing that animates six circles rotating around a central point:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RotatingCirclesAnimation extends JPanel implements ActionListener {
private Timer timer;
private double angle = 0;
private int radius = 100;
private int numCircles = 6;
private int circleDiameter = 50;
public RotatingCirclesAnimation() {
timer = new Timer(16, this); // Update every 16 milliseconds (60 FPS)
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
for (int i = 0; i < numCircles; i++) {
double theta = angle + (2 * Math.PI * i / numCircles);
int x = (int) (centerX + radius * Math.cos(theta)) - circleDiameter / 2;
int y = (int) (centerY + radius * Math.sin(theta)) - circleDiameter / 2;
g2d.setColor(Color.getHSBColor((float) i / numCircles, 1.0f, 1.0f));
g2d.fillOval(x, y, circleDiameter, circleDiameter);
}
}
@Override
public void actionPerformed(ActionEvent e) {
angle += Math.PI / 180; // Increment angle to rotate circles
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Rotating Circles Animation");
RotatingCirclesAnimation animation = new RotatingCirclesAnimation();
frame.add(animation);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
In this code:
The
RotatingCirclesAnimation
class extendsJPanel
and implementsActionListener
.A
Timer
is used to update the angle every 16 milliseconds, creating a smooth 60 FPS animation.The
paintComponent
method calculates the positions of six circles based on the angle and draws them.The
actionPerformed
method updates the angle to rotate the circles and repaints the panel.The
main
method sets up the JFrame and adds the animation panel to it.
Feel free to experiment and customize the code to suit your needs. Enjoy creating your animation! If you have any more questions or need further assistance, I'm here to help.
Tidak ada komentar:
Posting Komentar