i have the following code for animating a ball from top left corner towards the bottom right corner.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class MainFrame{
int i=0,j=0;
JFrame frame = new JFrame();
public void go(){
Animation anim = new Animation();
anim.setBackground(Color.red);//Why color is not changing to red for the panel.
frame.getContentPane().add(anim);
frame.setVisible(true);
frame.setSize(475,475);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for(i=0,j=0;i<frame.getHeight()&&j<frame.getWidth();++i,++j){
anim.repaint();//Main problem is here,described below.
try{
Thread.sleep(50);
}
catch(Exception ex){}
}
}
public static void main(String[] args) {
MainFrame mf = new MainFrame();
mf.go();
}
class Animation extends JPanel{
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g;
g.fillOval(i,j,25,25);
}
}
}
Questions
- When i do
anim.repaint()
inside the methodgo
i don't get the ball animating from top left corner to bottom right corner but it gets smeared down the path.But if i replace it withframe.repaint()
i get the desired result that is a moving ball.So what is the difference between these two calls torepaint
? - Why the color of panel is not changing after
anim.setBackground(Color.red);
ingo
method? - If you run this programe you will find that the ball is not exactly going at the bottom edge,so how can i acheive that?