import java.applet.*;
import java.awt.*; // Graphics, Shape
import java.awt.geom.*; //Graphics2D
/*
<applet code = Oval1.class height=300 width=300 >
</applet>
*/
public class Oval1 extends Applet implements Runnable {
Shape circle;
Color c;
public void init() {
circle = new Ellipse2D.Float(90,100, 90, 90);
repaint();
Thread th = new Thread(this);
th.start();
}
public void run() {
try {
while(true) {
System.out.println(1);
c = Color.cyan;
repaint();
Thread.sleep(1000);
System.out.println(2);
c = Color.gray;
repaint();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
Graphics2D d = (Graphics2D) g;
d.setColor(c);
d.fill(circle);
}
}
我正在尝试创建一个applet,它在applet中间有一个填充圆圈&amp;每秒钟改变圆圈的颜色,意味着我想要显示圆圈,就像它闪烁一样。
我想每秒都改变圆圈的颜色。
为此我使用Shape class&amp;线程,但它仍然无法正常工作。
我已经尝试通过覆盖更新方法来使用paint(g)
。
这也不会影响
答案 0 :(得分:3)
在第二次重绘()之后添加Thread.sleep(1000)。
while(true) {
System.out.println(1);
c = Color.cyan;
repaint();
Thread.sleep(1000);
System.out.println(2);
c = Color.gray;
repaint();
Thread.sleep(1000);
}
答案 1 :(得分:2)
您可以使用Java Timer代替Thread.sleep()。例如,使用Timer http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html。 Thread.sleep()块小程序的绘制方法。
答案 2 :(得分:1)
尝试这个..
只需要在第二次重绘()之后放置 Thread.sleep(1000); ,目前在第二次重绘之后立即第一次重新调用,所以它在第二次重绘(); 强>
import java.applet.*;
import java.awt.*; // Graphics, Shape
import java.awt.geom.*; //Graphics2D
/*
<applet code = Oval1.class height=300 width=300 >
</applet>
*/
public class Oval1 extends Applet implements Runnable {
Shape circle;
Color c;
public void init() {
circle = new Ellipse2D.Float(90,100, 90, 90);
repaint();
Thread th = new Thread(this);
th.start();
}
public void run() {
try {
while(true) {
System.out.println(1);
c = Color.cyan;
repaint();
Thread.sleep(1000);
System.out.println(2);
c = Color.gray;
repaint();
Thread.sleep(1000);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
Graphics2D d = (Graphics2D) g;
d.setColor(c);
d.fill(circle);
}
}