-1

What's the problem in my code while generating a simple animation, where a green ball moves from the top left corner of the window diagonally downwards. But what i am getting is ball appears at the screen after a long time and it just remains stationary.What can i do?

import javax.swing.*;
import java.awt.*;
class Show_starter
{

int x, y;
JFrame window = new JFrame("Graphic_show");
Graphic_panel jp = new Graphic_panel();

public static void main(String[] args) {

    Show_starter start = new Show_starter();
    start.go();

}

private void go()
{

    window.getContentPane().add(BorderLayout.CENTER, jp);
    window.setSize(600,800);
    window.setVisible(true);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

class Graphic_panel extends JPanel
{

    public void paintComponent(Graphics g)
    {

        for ( int i = 0; i < 100; ++i){
            g.setColor(Color.white);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            g.setColor(Color.green);
            g.fillOval(x, y, 40, 40);

            x++;
            y++;

            try{

                Thread.sleep(50);
            }catch (Exception e){}

            jp.repaint();

        }

    }
}

EDIT: i am calling repaint() also but its not working.

OldSchool
  • 2,123
  • 4
  • 23
  • 45
  • You will want to do some searching for similar questions in the future as this gets asked a lot, and just a simple Google search will find the problem and solution quickly. Question closed as a duplicate. – Hovercraft Full Of Eels Jul 28 '15 at 11:37
  • Also please look at [this question and its answers](http://stackoverflow.com/questions/23393664/swing-repaint-doesnt-work-in-loop-or-thread) for a similar issue, this time due to a `while (true)`. – Hovercraft Full Of Eels Jul 28 '15 at 11:43

1 Answers1

2

It should come as no surprise that nothing moves -- your Thread.sleep(...) is freezing the paintComponent method which will freeze all painting and in fact should completely freeze your GUI. Check similar questions on this site (it gets asked a lot), and you'll see a similar answer: use a Swing Timer to drive your animation.

Also:

  • Don't forget to call the super.paintComponent(g); method in your override. This will allow the JPanel to repaint itself, covering any old pixels.
  • Never call repaint() from within a painting method. This results in terrible and completely uncontrolled animation.
  • Do read the Swing Painting Tutorials and Swing Timer tutorial.
  • Do read Concurrency in Swing to learn more about the details of Swing threading.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373