GUI Starter Kit
David Matuszek, Fall 2003

These examples are provided for your use. A good way to get started on an assignment is simply to take the most appropriate of these, get it running, then gradually modify it until it does what you want. With a little practice, you should be able to write programs with GUIs from scratch.

Applets:

If you only do drawing on an applet, then you can draw directly on the applet itself (which is a Panel). In this case, the only method you need to supply is a public void paint(Graphics g) method.

import java.applet.Applet;
import java.awt.*;


public class AppletDraw extends Applet {


    public void paint(Graphics g) {
        for (int i = 20; i < 200; i += 10) {
            g.drawRect(i, i, 150, 150);
        }
    }
}

You can try this applet out if you like; just copy the text into a file named AppletDraw. (In BlueJ, create an Applet class named AppletDraw, and replace the text of that file with this text.)

If you don't mind "sharing space" with controls, you can even do so, but it's generally not a good idea, because you have to be very careful about what gets covered up by what.

import java.applet.Applet;
import java.awt.*;


public class AppletDraw extends Applet {


    public void init() {
        add(new TextArea("Nobody ever listens to me!", 12, 40));
    }

    public void paint(Graphics g) {
        for (int i = 20; i < 200; i += 10) {
            g.drawRect(i, i, 150, 150);
        }
    }
}

Usually, though, if you want to do drawing, you should do so in a separate area of the window. The Canvas component is designed for this. To use a Canvas, you must subclass the Canvas class and override its public void paint(Graphics g) method. Then, when you want to change what is painted there, you must call your Canvas object's repaint() method. Here's an example:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;


public class CanvasDraw extends Applet {
    MyCanvas myCanvas = new MyCanvas();
    Button colorButton = new Button("Change Color");
    static Random random = new Random();
    Color lineColor = Color.blue;
    
    public void init() {
        setLayout(new BorderLayout());
        add(myCanvas, BorderLayout.CENTER);
        add(colorButton, BorderLayout.SOUTH);
        
        colorButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                lineColor = new Color(random.nextInt(256),
                                      random.nextInt(256),
                                      random.nextInt(256));
                myCanvas.repaint();
        }});
    }
    
    class MyCanvas extends Canvas {
        public void paint(Graphics g) {
            g.setColor(lineColor);
            for (int i = 20; i < 200; i += 10) {
                g.drawRect(i, i, 150, 150);
            }
        }
    }
}

The previous example uses an anonymous inner class to listen for button clicks, because it's convenient and the code is short, but it uses a member class for MyCanvas, because this method could be quite long. Which kind of class you use is a matter of style, not a Java requirement.

It is not unusual to subclass Panel rather than Canvas. Everything else works just as above, but since a Panel is a Container, this gives you the option of overlaying your drawing with controls of some sort

Applications:

You have a little more to do in an application than in an applet. When you run an applet, the applet Panel is given to you "for free," and you don't need to worry about quitting the applet. When you write an application, you have to do everything yourself.

To get a window in the first place, you should write a class that extends Frame. (A Frame is like a Panel, but the default layout manager is BorderLayout instead of FlowLayout.) Populate the frame with Components, as usual.

A frame object is just an object, and creating one doesn't cause anything to appear on the screen. To make it appear, you should do two things: set the size of the frame (not required, but recommended), and make it visible:

    setSize(500, 500);
    setVisible(true);

Windows have a close box (looks like X ) in the upper-right-hand corner. When this is clicked, the window should close (and, in many cases, the program should exit). To do this, you need to attach a listener to the close box. Here is a statement to attach a listener, and a convenient little class for the listener itself:

    addWindowListener(new ClosingWindow());


    class ClosingWindow extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }

Putting this all together, we get:

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class DrawingFrame extends Frame {
    MyCanvas myCanvas = new MyCanvas();
    Button colorButton = new Button("Change Color");
    static Random random = new Random();
    Color lineColor = Color.blue;
    boolean running = true;
	
	public static void main(String[] args) {
	    DrawingFrame frame = new DrawingFrame();
	    frame.setup();
	}
	
	void setup() {
        setLayout(new BorderLayout());
        add(myCanvas, BorderLayout.CENTER);
        add(colorButton, BorderLayout.SOUTH);
        
        colorButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                lineColor = new Color(random.nextInt(256),
                                      random.nextInt(256),
                                      random.nextInt(256));
                myCanvas.repaint();
        }});
        
        addWindowListener(new ClosingWindow());
        
        setSize(500, 500);
        setVisible(true);
    }
    
    class MyCanvas extends Canvas {
        public void paint(Graphics g) {
            g.setColor(lineColor);
            for (int i = 20; i < 200; i += 10) {
                g.drawRect(i, i, 150, 150);
            }
        }
    }
    
    class ClosingWindow extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }
}