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 |
|
Creates a new panel. |
|
Creates a new panel. If the parameter is |
|
Creates a new panel with the specified layout manager. The default layout manager is |
Methods
Method |
Description |
|
Adds the specified component to the panel. |
|
Removes the specified component from the panel. |
|
Sets the layout manager used to control how components are arranged when the panel is displayed. The default is the |
|
Sets the |
|
Sets the size of the frame to the specified width and height. |
|
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());