Hey TIGForums,
Today I will give you a brief tutorial on how to do animation in Java2D. First of all, you'll need a class file and the main() method.
package Draw;
import javax.swing.JFrame;
public class Draw {
public static void main(String[] args) {
}
}
Next, you'll need to put a JFrame inside the main method. Think of the JFrame as a blank canvas. (Not to be confused with the 'java.awt.Canvas' class, which I will not be using)
package Draw;
import javax.swing.JFrame;
public class Draw {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setTitle("Draw");
//frame.add(new GFX());
}
}
This puts a frame, 500x600 pixels, on your screen called "Draw" that cannot be resized.
Next, you need to add a class that will actually draw the graphics. You notice that I have that last 'frame.' line commented out, because that constructor doesn't exist. You can un-comment this line once you add this following code:
package Draw;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class GFX extends JPanel {
private static final long serialVersionUID = 1L;
int x, y;
public GFX() {
x = 1;
y = 1;
}
public void paint(Graphics g) {
g.setColor(Color.green);
for (int i = 0; i < 124; i++) {
g.fillRect(x, y, 32, 32);
x++;
y++;
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Then, uncomment the line that refers to the GFX class, and you should see a green square going in a diagonal pattern down the frame.
That's all for this tutorial, if you have any questions post them below or PM me.
Cheers!
-DarkCart