2
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);
    }
}

我正在尝试创建一个小程序,该小程序在小程序中间有一个实心圆圈并每秒更改圆圈的颜色,这意味着我想显示圆圈就像它在闪烁一样。

我想每秒改变圆圈的颜色。

为此,我使用 Shape 类和线程,但它仍然无法正常工作。

我已经尝试通过 paint(g)覆盖更新方法使用..

这也不会影响

4

3 回答 3

3

在第二次 repaint() 之后添加 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);
        }
于 2012-12-28T07:29:04.297 回答
2

您可以使用 Java Timer 代替 Thread.sleep()。例如使用 Timer,http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html。小程序的 Thread.sleep() 块绘制方法。

于 2012-12-28T07:21:37.890 回答
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);
    }
}
于 2014-07-08T12:15:14.107 回答