In part 1, all we did was set up a window. In part 2, I want to show how Graphics2D can be used to draw cool stuff.
Note: I won’t show the code for creating the window or looping through the frames. I’ll assume you either have that code or some other piece of code with a game loop and a Graphics2D object.
First I want to show how to use setColor() and drawLine(). There are many other drawing commands, check the Graphics2D Javadoc for the full list. Here is the code:
And here is what it draws:
The code is pretty straightforward here. I set the draw color to black, then fill a background. I then move the origin to the center of the screen, and set mag, the radius of the circle, and incAmt, the angle size of each “slice”.
The for block loops from 0 to 2PI. It first chooses a color, using the Color.getHSBColor() method. It then creates a Polygon object, and adds three points, one at the center, one at the edge of the circle, and one at the next edge. Finally it fills the polygon on the screen.
The next example is much simpler. Here is the code:
And here is what it looks like:
Note: I’m drawing this continually each frame, so I don’t fill a rectangle at the beginning to clear each frame. Also, I move the origin into the negative by the circles’ radius. This is because drawOval() draws from the top left, not from the center.
Each frame I choose a random color, and then draw it randomly on the screen. That’s It!






