Java Swing과 AWT를 이용하여 원 돌아가는 애니메이션 만들기
2022. 8. 16. 22:05ㆍJava/Swing
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Arc2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CircleAnimation extends JFrame {
JPanel jp;
int arc; // 각도
public CircleAnimation() {
super("Circle Animation");
this.setSize(500, 500);
this.setLocationRelativeTo(null);
this.add(jp = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.red);
g2d.fill(new Arc2D.Float(0, 0, getWidth(), getHeight(), 90, arc, Arc2D.PIE));
g2d.setColor(Color.white);
g2d.fillOval(40, 40, getWidth() - 80, getHeight() - 80);
}
});
jp.setBackground(Color.white);
this.setVisible(true);
new Thread(() -> {
while (arc <= 360) {
arc++;
repaint();
revalidate();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
public static void main(String[] args) {
new CircleAnimation();
}
}
Thread를 사용해서 arc (각도)를 계속 증가시켜주고, Arc2D를 사용하여 원을 그려준다.
덤으로 fillOval로 가운데 쪽 덮어줘서 마치 윈도우 타이머 애니메이션같이 보이게 만들었다..
만약 시계방향 쪽으로 가게 하고 싶다면 Arc2D 쪽의 arc를 -arc로 변경해주면 된다.