Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Using Components, the GUI Building Blocks

How to Use Panels

The Panel(in the API reference documentation) class is a general-purpose Container subclass. You can use it as-is to hold Components, or you can define a subclass to perform special functionality, such as event handling for the objects the Panel contains.

The Applet(in the API reference documentation) class is a Panel subclass with special hooks to run in a browser or other applet viewer. Whenever you see a program that can run both as an applet and as an application, chances are that it defines an Applet subclass but doesn't use any of the special Applet capabilities, relying instead on the methods it inherits from the Panel class.

Here's an example of using a Panel instance to hold some Components:

Panel p1 = new Panel();
p1.add(new Button("Button 1"));
p1.add(new Button("Button 2"));
p1.add(new Button("Button 3"));
Here's an example of a Panel subclass that draws a frame around its contents. Versions of this class are used by Examples 1 and 2 in Drawing Shapes(in the Creating a User Interface trail).
class FramedArea extends Panel {
    public FramedArea(CoordinatesDemo controller) {
	...//Set the layout manager.
	   //Add any Components this Panel contains...
    }

    //Ensure that no Component is placed on top of the frame.
    //The inset values were determined by trial and error.
    public Insets insets() {
        return new Insets(4,4,5,5);
    }

    //Draw the frame at this Panel's edges.
    public void paint(Graphics g) {
        Dimension d = size();
        Color bg = getBackground();
 
        g.setColor(bg);
        g.draw3DRect(0, 0, d.width - 1, d.height - 1, true);
        g.draw3DRect(3, 3, d.width - 7, d.height - 7, false);
    }
}

Many of the examples in this lesson use Applet subclasses to handle events for the Components they contain. You can see an example in How to Use Dialogs(in the Creating a User Interface trail). You can use the event handling in this and other examples as a model for event handling in your own Applet or Panel subclass.


Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Using Components, the GUI Building Blocks