xhtml
 

Custom Drawing

The Java 2D drawing facilities allow you to draw lines and curves, fill in areas, and draw text directly.  There is also a downloadable 3D package and various packages for drawing graphs, dealing with sounds, showing animations and video clips, and so on, which we won't discuss here.  Good sources of 2D information are the Java Tutorial

Java Tutorial: Custom Painting
Java Tutorial: 2D Graphics

and the Java 2D graphics demo that comes with the compiler (find your compiler installation directory, then the demo directory, then jfc, then Java2D, then run the Java2Demo.jar file by double clicking or by using the command java -jar Java2Demo.jar).

When you do your own drawing, you can't draw whenever you want to using your own code.  Instead, the graphics thread chooses when to draw, as with event handling.  That allows important optimisations such as drawing backgrounds before drawing what is in front.

Another complication is that you can't draw something just once.  If the window containing your drawing is covered up and then uncovered again, Java will ask you to re-draw.

This leads to a general strategy for a drawing.  You store the data which describes the drawing in some way, so that you can re-draw from this data at any time.   To change the drawing, you change the data and tell Java that the drawing has changed, so that it will ask you to do the redrawing at the next convenient opportunity.  Typically, you write a separate class in a separate file for a drawing, because drawing code tends to get complex.  Here is a drawing of a brick:

FramedBrick.java Brick.java
...
setPreferredSize(new Dimension(400, 300));
setMinimumSize(new Dimension(400, 300));
setMaximumSize(new Dimension(400, 300));
rectangle = new Rectangle(180,135,40,30);
...
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(rectangle);
...

The Brick class extends JPanel, which is the most convenient class providing a blank drawing area.  The setup code in the constructor gives the component a size and some hints about how much it likes to be squashed or stretched if the user resizes the main window.  (The hints are not honoured by the frame, so it would be better to put the brick in a box and the box in the frame, or to detect the size of the panel and compute the position to draw the brick at to keep it centred.)

All coordinates are measured rightwards and downwards from the top left hand corner of the local current window object that you are drawing into.

The paintComponent method is the one that Java will call when it wants you to redraw.  This starts with two standard lines, first a call to super.paintComponent to make sure that any default painting gets done, then a cast from the old Graphics type to the new Graphics2D type. Then it draws the picture using the global data.

See the Shape interface and the classes which implement it for other things you can use in drawings besides rectangles.


Back