Appendix B. Java 2D Graphics
The Java library includes a simple package for drawing 2D graphics, called java.awt. AWT stands for “Abstract Window Toolkit”. We are only going to scratch the surface of graphics programming; you can read more about it in the Java tutorials at https://docs.oracle.com/javase/tutorial/2d/.
Creating Graphics
There are several ways to create graphics in Java; the simplest way is to use java.awt.Canvas and java.awt.Graphics. A Canvas is a blank rectangular area of the screen onto which the application can draw. The Graphics class provides basic drawing methods such as drawLine, drawRect, and drawString.
Here is an example program that draws a circle using the fillOval method:
importjava.awt.Canvas;importjava.awt.Graphics;importjavax.swing.JFrame;publicclassDrawingextendsCanvas{
publicstaticvoidmain(String[]args){JFrameframe=newJFrame("My Drawing");Canvascanvas=newDrawing();canvas.setSize(400,400);frame.add(canvas);frame.pack();frame.setVisible(true);}publicvoidpaint(Graphicsg){g.fillOval(100,100,200,200);}}
The Drawing class extends Canvas, so it has all the methods provided by Canvas, including setSize. You can read about the other methods in the documentation, which you can find by doing a web search for “Java Canvas”.
In the main method, we:
Create a
JFrameobject, which is the window that will contain the canvas.Create a
Drawingobject (which is the canvas), set its width and height, and add it to the frame. ...