0% found this document useful (0 votes)
51 views1 page

3 - JPanel Basic Tutorial and Examples

The document provides a comprehensive tutorial on JPanel, a lightweight container in Java's Swing framework, detailing its creation, layout management, component addition, and customization. It includes code examples for creating a JPanel, setting layouts, adding components, and integrating it into a parent container. Additionally, a sample application is presented to demonstrate typical usage of JPanel in a login panel context.

Uploaded by

ahmedkhwaja193
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views1 page

3 - JPanel Basic Tutorial and Examples

The document provides a comprehensive tutorial on JPanel, a lightweight container in Java's Swing framework, detailing its creation, layout management, component addition, and customization. It includes code examples for creating a JPanel, setting layouts, adding components, and integrating it into a parent container. Additionally, a sample application is presented to demonstrate typical usage of JPanel in a login panel context.

Uploaded by

ahmedkhwaja193
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

CodeJava

Coding Your Passion


Java Core Java SE Java EE Spring Framework Spring Boot Spring Security Hibernate AWS REST APIs

All Tutorials 🔍
Home > Java SE > Swing

JPanel basic tutorial and examples


Written by Nam Ha Minh
Last Updated on 06 July 2019 | Print Email

JPanel is a Swing’s lightweight container which is used to group a set of components together. JPanel
is a pretty simple component which, normally, does not have a GUI (except when it is being set an
opaque background or has a visual border).

In this article, we summarize the common practices when working with JPanel in Swing. At the end, we
will create a sample program looks like this:

Table of content:
1. Creating a new JPanel
2. Setting a layout manager
3. Adding components to the panel
4. Adding the panel to a parent container
5. Customizing appearance
6. Sample application

1. Creating a new JPanel


The JPanel class resides in the package javax.swing and it’s a subclass of the
javax.swing.JComponent class.

Normally we create new JPanel object as simple as follows:

1 JPanel newPanel = new JPanel();

That creates a new JPanel with double enabled by default.


Often, we create a class that extends from JPanel as follows:

1 public class UserDetail extends JPanel {


2
3 // code to add components to the panel
4
5 }

If we want to specify the double buffering strategy explicitly, use the constructor JPanel(boolean
isDoubleBuffered):

1 JPanel newPanel = new JPanel(true); // enable double buffering


2
3 JPanel newPanel = new JPanel(false); // disable double buffering

We also can specify a layout manager when creating the panel:

1 JPanel newPanel = new JPanel(new GridBagLayout());


2 JPanel newPanel = new JPanel(new BorderLayout());

By default, the panel has a flow layout manager.


Another constructor allows us to specify both the double buffering strategy and a layout manager:

1 // use grid bag layout and no double buffering:


2 JPanel newPanel = new JPanel(new GridBagLayout(), false);

2. Setting a layout manager for JPanel


We can call the method setLayout(LayoutManager)to specify a layout manager for the panel (after
the panel is created):

1 JPanel newPanel = new JPanel();


2 newPanel.setLayout(new GridBagLayout());

However it’s recommended to specify the layout manager when creating the panel to avoid creating
the default FlowLayout object:

1 // NOT recommended:
2 JPanel newPanel = new JPanel(); // a FlowLayout manager is created by default
3 newPanel.setLayout(new GridBagLayout());
4
5 // RECOMMENDED:
6 JPanel newPanel = new JPanel(new GridBagLayout());

One exception is the BoxLayout, whose constructor requires an existing container, so we cannot
specify a BoxLayout when creating the panel. For example:

1 // exception:
2 JPanel newPanel = new JPanel();
3 newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS));

3. Adding components to JPanel


To add GUI components such as JLabel, JTextField, JButton... to the panel, we use the add() method.
There are different versions of the add() method, so which method to be used is depending on the
layout manager of the panel.

Use the add(Component) method for the following layout managers: FlowLayout, BoxLayout,
GridLayout, or SpringLayout. For example:

1 JLabel label = new JLabel("Enter username:");


2 JTextField userName = new JTextField(20);
3
4 newPanel.add(label);
5 newPanel.add(userName);

Use the add(Component comp, Object constraints) method for the following layout managers:
BorderLayout, CardLayout or GridBagLayout. For example:

1 JPanel newPanel = new JPanel(new BorderLayout());


2 JLabel label = new JLabel("Enter username:");
3 JTextField userName = new JTextField(20);
4
5 newPanel.add(label, BorderLayout.NORTH);
6 newPanel.add(userName, BorderLayout.SOUTH);

For GridBagLayout, we have to pass a GridBagConstraintsobject as the second argument. For


example:

1 GridBagConstraints constraints = new GridBagConstraints();


2 constraints.anchor = GridBagConstraints.WEST;
3 constraints.insets = new Insets(10, 10, 10, 10);
4 constraints.gridx = 0;
5 constraints.gridy = 0;
6
7 newPanel.add(labelUsername, constraints);

For CardLayout, use the add(String name, Component comp) method with the first argument is
name of a card. For example:

1 JPanel wizardPanel = new JPanel(new CardLayout());


2 wizardPanel.add("Step1", step1Panel);
3 wizardPanel.add("Step2", step2Panel);

4. Adding JPanel to a parent container


The panel cannot stand alone. It must be added to a parent container such as a JFrame or another
JPanel. For example:

1 frame.add(newPanel);
2 anotherPanel.add(newPanel);

5. Customizing appearance for JPanel


Normally, a JPanel does not render its own GUI. However we can set its background color, transparent
background or border when necessary.

Set background color:

1 newPanel.setBackground(Color.CYAN);

Set transparent background:

1 newPanel.setOpaque(false); // make transparent background

By default, the panel’s background is opaque.


Set a raised bevel border:

1 newPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));

Set an etched border:

1 newPanel.setBorder(BorderFactory.createEtchedBorder());

Set a line border:

1 newPanel.setBorder(BorderFactory.createLineBorder(Color.RED));

Set a titled and etched border:

1 newPanel.setBorder(BorderFactory.createTitledBorder(
2 BorderFactory.createEtchedBorder(), "Login Panel"));

6. JPanel Sample application


We created the following program to demonstrate the typical usages of JPanel in a Swing application.
The program uses a JPanel to group some labels, textfields and a button to form a login panel as
follows:

As you can notice, the panel used in this program has a titled border “Login Panel”. Here is complete
source code of the program:

1 package net.codejava.swing.jpanel;
2
3 import java.awt.GridBagConstraints;
4 import java.awt.GridBagLayout;
5 import java.awt.Insets;
6
7 import javax.swing.BorderFactory;
8 import javax.swing.JButton;
9 import javax.swing.JFrame;
10 import javax.swing.JLabel;
11 import javax.swing.JPanel;
12 import javax.swing.JPasswordField;
13 import javax.swing.JTextField;
14 import javax.swing.SwingUtilities;
15 import javax.swing.UIManager;
16
17 /**
18 * This program demonstrates how to use JPanel in Swing.
19 * @author www.codejava.net
20 */
21 public class SwingJPanelDemo extends JFrame {
22
23 private JLabel labelUsername = new JLabel("Enter username: ");
24 private JLabel labelPassword = new JLabel("Enter password: ");
25 private JTextField textUsername = new JTextField(20);
26 private JPasswordField fieldPassword = new JPasswordField(20);
27 private JButton buttonLogin = new JButton("Login");
28
29 public SwingJPanelDemo() {
30 super("JPanel Demo Program");
31
32 // create a new panel with GridBagLayout manager
33 JPanel newPanel = new JPanel(new GridBagLayout());
34
35 GridBagConstraints constraints = new GridBagConstraints();
36 constraints.anchor = GridBagConstraints.WEST;
37 constraints.insets = new Insets(10, 10, 10, 10);
38
39 // add components to the panel
40 constraints.gridx = 0;
41 constraints.gridy = 0;
42 newPanel.add(labelUsername, constraints);
43
44 constraints.gridx = 1;
45 newPanel.add(textUsername, constraints);
46
47 constraints.gridx = 0;
48 constraints.gridy = 1;
49 newPanel.add(labelPassword, constraints);
50
51 constraints.gridx = 1;
52 newPanel.add(fieldPassword, constraints);
53
54 constraints.gridx = 0;
55 constraints.gridy = 2;
56 constraints.gridwidth = 2;
57 constraints.anchor = GridBagConstraints.CENTER;
58 newPanel.add(buttonLogin, constraints);
59
60 // set border for the panel
61 newPanel.setBorder(BorderFactory.createTitledBorder(
62 BorderFactory.createEtchedBorder(), "Login Panel"));
63
64 // add the panel to this frame
65 add(newPanel);
66
67 pack();
68 setLocationRelativeTo(null);
69 }
70
71 public static void main(String[] args) {
72 // set look and feel to the system look and feel
73 try {
74 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
75 } catch (Exception ex) {
76 ex.printStackTrace();
77 }
78
79 SwingUtilities.invokeLater(new Runnable() {
80 @Override
81 public void run() {
82 new SwingJPanelDemo().setVisible(true);
83 }
84 });
85 }
86 }

You can download the code as well as an executable jar file of this program in the attachments section.

Other Java Swing Tutorials:


Java Swing Hello World Tutorial for Beginners Using Text Editor
JFrame basic tutorial and examples
JLabel basic tutorial and examples
JTextField basic tutorial and examples
JButton basic tutorial and examples
JComboBox basic tutorial and examples
JCheckBox basic tutorial and examples
JList basic tutorial and examples
JTree basic tutorial and examples

About the Author:


Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming
with Java back in the days of Java 1.4 and has been passionate about it ever since. You
can connect with him on Facebook and watch his Java videos on YouTube.

Attachments:
SwingJPanelDemo.zip [Source code and runnable jar file] 7 kB

Add comment
Name E-mail
comment

Notify me of follow-up comments

Send
Comments
1 2 3

#15michael 2020-04-29 18:31


Hi, i wrote a test class to change the text on container elements. I tried with Resource Bundle and
Input Stream. If i change elements the are placed direct on the frame it's not a problem but if i try to
change a label(here label2) that's placed on a panel i become a null pointer exception.
Quote

#14saliza 2020-02-10 20:56


if i want to move my panel at the left side..how i want to do
Quote

#13sheetal.joshi86@gmai 2020-02-05 05:29


hi
i have used JPANEL
JOptionPane.showConfirmDialog() IN java file do get confirmation and accordingly function has
been called.it works fine on my PC .But after war deployment it does not pop up for confirmation
.....
Quote

#12irene jalalon 2019-10-02 06:53


nice thank you for this code
Quote

#11Nabil 2019-02-03 10:48


I have two Jframes (A,B) and each Frame has Jpanel(Ap,Bp) .I want call jPanel Ap only from
Jframe B ????
Quote

1 2 3

Refresh comments list

See All Java Tutorials

CodeJava.net delivers Java tutorials, code examples and sample projects for programmers at any level of expertise.
This site is founded and maintained by Nam Ha Minh - a highly passionate and skilled programmer.

Home About Contact Terms of Use Privacy Policy Facebook Twitter YouTube GitHub

Copyright © 2012 - 2025 CodeJava.net, all rights reserved.

You might also like