Having trouble with a simple animation
I'm trying to write a simple animation but I'm having serious trouble trying to understand the concepts, the animation itself does not matter (it's just a simple line) , I just want to see something "moving" on the screen.
The problem is in adding the line to the panel I'm also having trouble in the main method, I'd appreciate it if someone could help me, thanks.
Code :
import java.awt.*;
import javax.swing.*;
public class NewClass extends JComponent implements Runnable {
int i = 1;
public void paint(Graphics g) {
i++;
g.drawLine(i,50 ,50,50);
repaint();
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
class classs {
public static void main(String args[]) {
NewClass p = new NewClass();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
}
Re: Having trouble with a simple animation
a) Override paintComponent, not paint b) Do not call repaint within either paint or paintComponent - this should be called during the animation (in your animation thread or Swing Timer) c) You must add the component you are painting to to the displayed component (your JFrame or the components it contains) d) You implement Runnable, but never use it (you must start a thread to do so) e) You might want to consider using a Swing Timer to do the painting. I know these are a lot of pieces of advice, but take them one step at a time. First get your item displayed (add it to the JPanel or JFrame), then work from there.
Re: Having trouble with a simple animation
Thanks copeg, yes it's a lot to take care of but I'll do what you suggested, one step at a time.