CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Swing

Swing
Panels, buttons and events
Add a panel to a frame

How to add a panel to a frame

  • A JFrame object contains several panes.
  • To add components to a frame, you add them to the content pane of the frame.
  • A panel is a component that's used as a container for other components.
  • The normal way to build a Swing user interface is to create a panel, add components such as labels, text boxes, and buttons to the panel, then add the panel to the content pane.

Method needed to add components to the content pane with Java 5

Class Method Description
JFrame add(Component) Adds a component to the frame's content pane.

A JFrame constructor that adds a panel to the content pane with Java 5

class FutureValueFrame()
{
    setTitle("Future Value Calculator");
    setSize(267, 200);
    centerWindow(this);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    this.add(panel);
}

Methods needed to add components to the content pane prior to Java 5

Class Method Description
JFrame getContentPane() Returns a Container object that represents the content pane.
Container add(Component) Adds a component (such as a JPanel) to this Container.

Code for adding a panel to the content pane prior to Java 5

Container contentPane = this.getContentPane();
contentPane.add(panel);
Previous | Add a panel to a frame | Add buttons to a panel | Handle button events | Next