作为我的编程任务的一部分,我必须在小程序中显示一个旋转的风扇。
这是我的代码(显示风扇的类):
import javax.swing.*;
import java.awt.*;
public class Fan extends JPanel
{
private int angle1 = -15;
private int angle2 = 75;
private int angle3 = 165;
private int angle4 = 255;
public Fan()
{
this.setSize(600, 400);
Runnable spinner = new SpinFan();
Thread thread1 = new Thread(spinner);
thread1.start();
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(200, 150, 150, 150);
g.fillArc(210, 160, 130, 130, angle1, 30);
g.fillArc(210, 160, 130, 130, angle2, 30);
g.fillArc(210, 160, 130, 130, angle3, 30);
g.fillArc(210, 160, 130, 130, angle4, 30);
}
}
class SpinFan implements Runnable
{
@Override
public void run()
{
try
{
while(true)
{
angle1 = (angle1 + 1) % 360;
angle2 = (angle2 + 1) % 360;
angle3 = (angle3 + 1) % 360;
angle4 = (angle4 + 1) % 360;
System.out.println(angle1 + " " + angle2 + " " + angle3 + " " + angle4);
repaint();
Thread.sleep(10);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem while putting thread to sleep.");
}
}
}
进一步处理的类(现在只有 Fan 的实例):
import java.awt.*;
import javax.swing.*;
public class FanControl extends JPanel
{
public FanControl()
{
add(new Fan());
}
}
最后,这是 Applet 类:
import java.awt.*;
import javax.swing.*;
public class FanApplet extends JApplet
{
public FanApplet()
{
add(new FanControl());
}
}
现在我一直在尝试各种各样的东西,所以请不要介意额外注释掉的代码。Fan.jav
a 类工作正常(如果我将它作为应用程序运行,将它放在框架中,我可以看到风扇在旋转)。但我就是无法让风扇在 Applet 中旋转。但是,如果我从 Fan.java 类向 Applet添加类似JButton的东西,它就可以工作。
我错过了什么?paintComponent()
使用线程和小程序或我似乎不知道的小程序时是否有一些并发症。
当我将代码作为应用程序运行时,它工作正常。我可以看到旋转的风扇。这是代码:
import javax.swing.*;
import java.awt.*;
public class Fan extends JPanel
{
private int angle1 = -15;
private int angle2 = 75;
private int angle3 = 165;
private int angle4 = 255;
public Fan()
{
Runnable spinner = new SpinFan();
Thread thread1 = new Thread(spinner);
thread1.start();
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.add(new Fan());
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(200, 150, 150, 150);
g.fillArc(210, 160, 130, 130, angle1, 30);
g.fillArc(210, 160, 130, 130, angle2, 30);
g.fillArc(210, 160, 130, 130, angle3, 30);
g.fillArc(210, 160, 130, 130, angle4, 30);
}
class SpinFan implements Runnable
{
@Override
public void run()
{
try
{
while(true)
{
angle1 = (angle1 - 1) % 360;
angle2 = (angle2 - 1) % 360;
angle3 = (angle3 - 1) % 360;
angle4 = (angle4 - 1) % 360;
System.out.println(angle1 + " " + angle2 + " " + angle3 + " " + angle4);
repaint();
Thread.sleep(10);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem while putting thread to sleep.");
}
}
}
}