I have been experimenting with drawing on a JFrame, so I could use these experiments in the future for a program I might create. However, I have found a problem that I am not able to solve: How to draw stuff while having a timer set up.
public static void MyTimer() {
JFrame frame = new JFrame("Colors");
int width = 700;
int height = 700;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.BLACK);
frame.pack();
frame.setSize(width, height);
frame.setVisible(true);
frame.setResizable(false);
TimerTask task;
task = new TimerTask() {
int a = 2;
@Override
public void run(Graphics g) {
g.drawRect(a, 2, a + 66, 68);
g.fillRect(a, 2, a + 66, 68);
a = a + 20;
}
};
timer.schedule(task, 0, 1000);
}
As you can see, I am trying to draw a new square every second. The problem is, I get an error in the code:
method does not override or implement a method from a supertype
How can I fix this?
How can I fix this?
The run()
method does not take a parameter. Get rid of the Graphics parameter. That will get rid of the compile error.
However, that still will not help with your painting.
Instead you need to override the paintComponent(...)
method of a JPanel
then you add the panel to the frame. Then you use the Graphics object passed to the paintComponent() method to do your painting.
Read the section from the Swing tutorial on Custom Painting for more information and working examples to get you started.
Also you should NOT be using a TimerTask for animation. You should be using a Swing Timer. Then in the actionPerformed(...)
method of the ActionListener
you would change the properties of your custom painting (ie in your case add a new square object to be painted) and then invoke repaint()
on the panel.
, I am trying to draw a new square every second
Check out the DrawOnImage
example found in Custom Painting Approaches. It will show you how to add a Rectangle object to a BufferedImage.