Monday, July 7, 2008

Java Graphics--Start with a JFrame

Jerry introduces Pierre to the JFrame
In A Most Basic Graphics App I presented a skeleton program that's suitable as a starting point for a graphics application. It deserves some explanation before we add more to it.

There are two graphics "components" that appear in this program, a JPanel and a JFrame. Why use both? If we want a really basic graphics app, why isn't one or the other enough?

If we're going to choose between the two, we'd have to take the JFrame. A Frame component is a special graphics component that lives on top of the host computer's graphics system. In Java it's called a "heavyweight" component. The "backboard" on which you draw, or place other components, has to be a heavyweight component. Only a heavyweight component can be guaranteed to be drawn correctly when placed directly on the user's display. Lightweight components have to be placed on top of a heavyweight component.

Since JPanel is a lightweight component, we can't use it without a heavyweight like JFrame to place it on. So if we're just picking one component, it's going to be the JFrame:

import java.awt.*;
import javax.swing.*;

public class JustaFrame extends JFrame{

public JustaFrame(){

public void paint(Graphics g){

public static void main(String[] arg){
JustaFrame frame = new JustaFrame();


You'll notice a problem here if you run the program. The "window decorations" for the title bar, window borders, and so on take away a piece of the space from the drawing area. Unless you've got pretty narrow title bars on your system, the line drawn by this program will start up underneath the title bar.

It's possible to find out how much space these items take up, and compensate. Or you can add another component in the visible drawing area as I did with the JPanel in the original program.

There's another difference here. The drawing is done by a paint() method, rather than a paintComponent() method. This is part of the difference between different types of components. If you change paint() into paintComponent() this program will compile and run, but it won't draw the line.

Later, we'll talk about the magic behind the paint() and paintComponent() methods and some of the other hidden mysteries of Java's graphics.