使用以下代码补全完成转动的圆代码设计并且一直转顺时针转完一圈逆时针继续转 import javax.swing.*; import java.awt.*; public class DrawCircle extends JPanel implements Runnable{ int angle=0; Thread t; public DrawCircle(){ this.setPreferredSize(new Dimension(500,500)); this.setBackground(Color.blue); t=new Thread(this); t.start(); } public void paintComponent(Graphics g){ super.paintComponent(g); g.fillArc(50, 50, 300, 300, 0, angle); } public static void main(String args[]){ JFrame f=new JFrame("画扇形"); f.getContentPane().add(new DrawCircle()); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void run() { // TODO Auto-generated method stub try{ for(int i=0;i<10;i++){ Thread.sleep(100); angle=angle+30; repaint();//重画 重新调用paintComponent } }catch(Exception ex){ } } }
时间: 2024-01-18 21:02:34 浏览: 116
以下是转动的圆的完整代码:
```java
import javax.swing.*;
import java.awt.*;
public class DrawCircle extends JPanel implements Runnable {
int angle = 0;
boolean clockwise = true; // true表示顺时针转,false表示逆时针转
Thread t;
public DrawCircle() {
this.setPreferredSize(new Dimension(500, 500));
this.setBackground(Color.blue);
t = new Thread(this);
t.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillArc(50, 50, 300, 300, 0, angle);
}
public static void main(String args[]) {
JFrame f = new JFrame("画扇形");
f.getContentPane().add(new DrawCircle());
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(100);
if (angle == 360) {
clockwise = false;
} else if (angle == 0) {
clockwise = true;
}
if (clockwise) {
angle += 30;
} else {
angle -= 30;
}
repaint(); // 重画,重新调用paintComponent
}
} catch (Exception ex) {
}
}
}
```
这个程序会一直转动圆,先顺时针转完一圈,然后逆时针继续转动,如此往复。具体实现方式是,在run方法中不断地更新angle变量的值,当angle等于360时改变direction变量的值为false,表示开始逆时针转动;当angle等于0时改变direction变量的值为true,表示开始顺时针转动。同时,每次更新angle变量的值后,都调用repaint方法重新绘制圆形。
阅读全文