In this lesson, you will learn.
JPanel is a generic lightweight container in Java Swing and is used to organize and group other components inside a window.
| Constructor | Description |
|---|---|
JPanel() |
Creates a new JPanel with a flow layout. |
JPanel(LayoutManager layout) |
Creates a new JPanel with the specified layout manager. |
You can create JPanel by using the following code snippet:
class JPanelDemo extends JFrame
{
//Code
}
OR
class JPanelDemo {
JPanel obj;
public JPanelDemo()
{
obj = new JPanel();
}
}
package jpanel;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JPanelDemo extends JFrame
{
JPanel obj;
public JPanelDemo()
{
//Set properties of JFrame
setTitle("JPanel Demo");
setVisible(true);
setSize(300,200);
//Create a JPanel
obj = new JPanel();
//set the color of a JPanel
obj.setBackground(Color.pink);
//Adding a jpanel to the JFrame
add(obj);
}
public static void main(String[] args)
{
JPanelDemo jPanel = new JPanelDemo();
}
}
Output

By default, a panel is not visible on the frame. To make it visible, you need to set the properties, such as background color or border.
setDefaultCloseOperation, pack, and setVisible.
Default Layout Manager: BorderLayout
Purpose: To organize and group components within a container.Characteristics:
JFrame.
Default Layout Manager: FlowLayout
| Method Name | Description |
|---|---|
void add(Component comp) |
Adds the specified component to this container. |
void setLayout(LayoutManager mgr) |
Sets the layout manager for this container. |
void setVisible(boolean aFlag) |
Makes the component visible or invisible. |
void setEnabled(boolean enabled) |
Enables or disables the component. |
void setBorder(Border border) |
Sets the border of this panel. |
Border getBorder() |
Returns the border of this panel. |
void setToolTipText(String text) |
Registers the text to display in a tool tip. |
String getToolTipText() |
Returns the tooltip string that has been set with setToolTipText. |
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.