Java – Painting Shape Objects
Well we have taken a look at drawing and handling shape objects in VB.NET, why not take a look at how to draw them in Java?
Note: This tutorial is assuming you already know how to setup a JFrame or a JApplet, if not that tutorial will be here sometime next week. The tutorial will go over the use of the paint method using 2D graphics.
Create a new method, it should be named paint and take the parameter Graphics g. Like this:
public void paint(Graphics g) {
We must call the super class to be able to begin to use this method. This must be the first line of code after starting the method:
super.paint(g);
Next we can simply draw shapes, text, circles, etc. By doing it this way we can not control the shapes as easily (Cant make it return the width, height, x, y)
To draw text, its this:
g.drawString("TEXT!!!",5,55);
Where 5 is the x position on the frame, and 55 is the y position. So this is near the top left corner.
Next lets declare graphics 2D so we can handle our 2D graphics:
Graphics2D g2d = (Graphics2D)g;
So now for the fun part, lets declare a rectangle and draw it!
Rectangle square = new Rectangle(squareX, squareY, 30, 30);
Notice how I used variables for the X and Y position, while the width and height are static. The variables allow me to move this square around in my other method through the arrow keys. The arrow keys increment each one accordingly then it calls repaint();
To draw the square to the x and y position we set, its:
g2d.fill(square);
But wait, the square is black! I want red!
Easy, simply set the fill colour before filling it:
g2d.setColor(Color.red);
And finish off the method
}
Anytime we can make the method repaint the form by simply calling
repaint();
This can be called within a timer if the form needs to continuously refresh, or in your method to handle the arrow keys. If the game has continuous action, Timers may be the best choice. See Timers in Java W/Out Threads
Hope it helps!



