我可以问一下如何反复重绘()吗?

时间:2013-03-03 07:05:02

标签: java swing paint repaint paintcomponent

对不起,我可以问一下java重复重复的问题, 我遇到了一个麻烦,我反复使用起草来表达Pacman Open& Close嘴巴动作。 但这个程序只有一次不会动...... 有人可以帮我解决这个问题...... 非常非常感谢!:D

我的代码如下:

package Strive;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

class CDrawF extends JFrame {
    CDrawF (){
        setTitle("繪製各式圖形");                       //JFrame interface
        setBounds(50, 50, 490, 260);        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        for(int i = 0; i<= 360; i++){              //repeatly 360 times
        repaint();
        g2.setColor(new Color(1.0f, 0.0f, 1.0f));               
        g2.fill(new Arc2D.Double(100, 100, 80, 80, 30, 300, Arc2D.PIE)); 
        //PacMan close mouth
        repaint();
        try{            //Delay setions
                Thread.sleep(1000);
             }catch(InterruptedException ex){}
        g2.fill(new Arc2D.Double(100, 100, 80, 80, 10, 340, Arc2D.PIE)); 
        //PacMan open mouth
        repaint();
        }
    }
}

public class NewClass {          //Main
    public static void main(String[] args){
        new CDrawF ();
    }
}

1 个答案:

答案 0 :(得分:9)

建议:

  • 不要直接在JFrame中绘图
  • 不要使用paint(...)方法绘制。
  • 永远不要在Swing事件线程上调用Thread.sleep(...)
  • 尤其不要使用paint(...)paintComponent(...)方法调用它。
  • 而是在JPanel或JComponent的paintComponent(...)方法中绘制
  • 阅读Java图形教程,因为他们将解释所有
  • 不要在paint(...)或paintComponent(...)
  • 中调用repaint()
  • 使用Swing Timer进行动画循环。教程再次帮助您完成此任务。