1

Excuse me,May I ask java repaint repeatlyed questions, I meet a trouble that I use drafting repeatedly to express Pacman Open&Close mouth motion. But this program Only once will not move... Somebody can help me to solve this problem... Very thanks so much!:D

My code as below:

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 ();
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
heyipomoea
  • 11
  • 3
  • possible duplicate of [Pacman open/close mouth animation](http://stackoverflow.com/questions/14426693/pacman-open-close-mouth-animation) – trashgod Mar 03 '13 at 07:09

1 Answers1

9

Suggestions:

  • Don't draw directly in the JFrame
  • Don't draw in the paint(...) method.
  • Never call Thread.sleep(...) on the Swing event thread
  • And especially don't call it in a paint(...) or paintComponent(...) method.
  • Instead draw in a JPanel or JComponent's paintComponent(...) method
  • Read the Java graphics tutorials as they will explain all of this.
  • Don't call repaint() inside of paint(...) or paintComponent(...)
  • Use a Swing Timer for your animation loop. Again the tutorials will help you do this.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373