JPanel Class

Package: javax.swing

The JPanel class defines a panel, which is a type of container designed to hold a group of components so they can be displayed in a frame. The normal way to display a group of controls — text fields, labels, buttons, and other GUI widgets — is to add those controls to a panel and then add the panel to the frame. You can bypass the panel and add the controls directly to the frame, but using a separate panel to hold the frame’s controls is almost always a good idea.

Constructors

Constructor

Description

JPanel()

Creates a new panel.

JPanel(boolean isDoubleBuffered)

Creates a new panel. If the parameter is true, the panel uses a technique called double buffering, which results in better display for graphics applications. This constructor is usually used for game programs or other panels that display animations.

JPanel(LayoutManager layout)

Creates a new panel with the specified layout manager. The default layout manager is FlowLayout.

Methods

Method

Description

void add(Component c)

Adds the specified component to the panel.

void remove(Component c)

Removes the specified component from the panel.

void setLayout (LayoutManager layout)

Sets the layout manager used to control how components are arranged when the panel is displayed. The default is the FlowLayout manager.

void setLocation(int x, int y)

Sets the x and y position of the frame onscreen. The top-left corner of the screen is 0, 0.

void setSize(int width, int height)

Sets the size of the frame to the specified width and height.

void setToolTipText(String text)

Sets the tooltip text that’s displayed if the user rests the mouse over an empty part of the panel.

The easiest way to create a panel and add it to a frame is to create a JPanel object, assign it to a variable in the JFrame constructor, add components to the panel, and then add the panel to the frame. Here’s an example:

// JFrame constructor

public HelloFrame()

{

this.setSize(200,100);

this.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);

this.setTitle(“Hello, World!”);

JPanel panel = new JPanel();

// code to add components to the panel

// goes here

this.setVisible(true);

}

Alternatively, you create a class that extends JPanel. Then you can add any components the panel needs in the constructor, as follows:

class HelloPanel extends JPanel

{

public HelloPanel()

{

// code to add components to the panel

// goes here

}

}

Then, in the frame class constructor, create a new instance of the panel class and add it to the panel:

this.add(new HelloPanel());

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset