The JPanel is a simplest container class. It provides space in which an application can attach any
other component. 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). It inherits the JComponents class. It doesn't have title bar.
JPanel class declaration
Class Constructors
Sr.No. | Constructor & Description |
---|---|
1 |
JPanel()
Creates a new JPanel with a double buffer and a flow layout.
|
2 |
JPanel(boolean isDoubleBuffered)
Creates a new JPanel with FlowLayout and the specified buffering strategy.
|
3 |
JPanel(LayoutManager layout)
Creates a new buffered JPanel with the specified layout manager.
|
4 |
JPanel(LayoutManager layout, boolean isDoubleBuffered)
Creates a new JPanel with the specified layout manager and buffering strategy.
|
Class Methods
Sr.No. | Method & Description |
---|---|
1 |
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JPanel.
|
2 |
PanelUI getUI()
Returns the look and feel (L&F) object that renders this component.
|
3 |
String getUIClassID()
Returns a string that specifies the name of the L&F class which renders this component.
|
4 |
protected String paramString()
Returns a string representation of this JPanel.
|
5 |
void setUI(PanelUI ui)
Sets the look and feel (L&F) object that renders this component.
|
6 |
void updateUI()
Resets the UI property with a value from the current look and feel.
|
Methods Inherited
This class inherits methods from the following classes −
- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
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
2
3
4
5
public
class
UserDetail
extends
JPanel {
// code to add components to the panel
}
- If we want to specify the double buffering strategy explicitly, use the constructor JPanel(boolean isDoubleBuffered):
1
2
3
JPanel newPanel =
new
JPanel(
true
);
// enable double buffering
JPanel newPanel =
new
JPanel(
false
);
// disable double buffering
- We also can specify a layout manager when creating the panel:
1
2
JPanel newPanel =
new
JPanel(
new
GridBagLayout());
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
2
// use grid bag layout and no double buffering:
JPanel newPanel =
new
JPanel(
new
GridBagLayout(),
false
);
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();
- Often, we create a class that extends from JPanel as follows:12345
public
class
UserDetail
extends
JPanel {
// code to add components to the panel
}
- If we want to specify the double buffering strategy explicitly, use the constructor JPanel(boolean isDoubleBuffered):123
JPanel newPanel =
new
JPanel(
true
);
// enable double buffering
JPanel newPanel =
new
JPanel(
false
);
// disable double buffering
- We also can specify a layout manager when creating the panel:12
JPanel newPanel =
new
JPanel(
new
GridBagLayout());
JPanel newPanel =
new
JPanel(
new
BorderLayout());
- Another constructor allows us to specify both the double buffering strategy and a layout manager:
1
2
| // use grid bag layout and no double buffering: JPanel newPanel = new JPanel( new GridBagLayout(), false ); |
2. Setting a layout manager
- We can call the method setLayout(LayoutManager)to specify a layout manager for the panel (after the panel is created):
1
2
JPanel newPanel =
new
JPanel();
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
2
3
4
5
6
// NOT recommended:
JPanel newPanel =
new
JPanel();
// a FlowLayout manager is created by default
newPanel.setLayout(
new
GridBagLayout());
// RECOMMENDED:
JPanel newPanel =
new
JPanel(
new
GridBagLayout());
- One exception is the BoxLayout, whose constructor requires an existing container, so we cannot specify a BoxLayoutwhen creating the panel. For example:
1
2
3
// exception:
JPanel newPanel =
new
JPanel();
newPanel.setLayout(
new
BoxLayout(newPanel, BoxLayout.X_AXIS));
- We can call the method setLayout(LayoutManager)to specify a layout manager for the panel (after the panel is created): 12
JPanel newPanel =
new
JPanel();
newPanel.setLayout(
new
GridBagLayout());
- However it’s recommended to specify the layout manager when creating the panel to avoid creating the default FlowLayout object: 123456
// NOT recommended:
JPanel newPanel =
new
JPanel();
// a FlowLayout manager is created by default
newPanel.setLayout(
new
GridBagLayout());
// RECOMMENDED:
JPanel newPanel =
new
JPanel(
new
GridBagLayout());
- One exception is the BoxLayout, whose constructor requires an existing container, so we cannot specify a BoxLayoutwhen creating the panel. For example:
1
2
3
| // exception: JPanel newPanel = new JPanel(); newPanel.setLayout( new BoxLayout(newPanel, BoxLayout.X_AXIS)); |
3. Adding components to the panel
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
2
3
4
5
JLabel label =
new
JLabel(
"Enter username:"
);
JTextField userName =
new
JTextField(
20
);
newPanel.add(label);
newPanel.add(userName);
- Use the add(Component comp, Object constraints) method for the following layout managers: BorderLayout, CardLayout or GridBagLayout. For example:
1
2
3
4
5
6
JPanel newPanel =
new
JPanel(
new
BorderLayout());
JLabel label =
new
JLabel(
"Enter username:"
);
JTextField userName =
new
JTextField(
20
);
newPanel.add(label, BorderLayout.NORTH);
newPanel.add(userName, BorderLayout.SOUTH);
- For GridBagLayout, we have to pass a GridBagConstraintsobject as the second argument. For example:
1
2
3
4
5
6
7
GridBagConstraints constraints =
new
GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets =
new
Insets(
10
,
10
,
10
,
10
);
constraints.gridx =
0
;
constraints.gridy =
0
;
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
2
3
JPanel wizardPanel =
new
JPanel(
new
CardLayout());
wizardPanel.add(
"Step1"
, step1Panel);
wizardPanel.add(
"Step2"
, step2Panel);
1
2
3
4
5
| JLabel label = new JLabel( "Enter username:" ); JTextField userName = new JTextField( 20 ); newPanel.add(label); newPanel.add(userName); |
1
2
3
4
5
6
| JPanel newPanel = new JPanel( new BorderLayout()); JLabel label = new JLabel( "Enter username:" ); JTextField userName = new JTextField( 20 ); newPanel.add(label, BorderLayout.NORTH); newPanel.add(userName, BorderLayout.SOUTH); |
1
2
3
4
5
6
7
| GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets( 10 , 10 , 10 , 10 ); constraints.gridx = 0 ; constraints.gridy = 0 ; newPanel.add(labelUsername, constraints); |
1
2
3
| JPanel wizardPanel = new JPanel( new CardLayout()); wizardPanel.add( "Step1" , step1Panel); wizardPanel.add( "Step2" , step2Panel); |
4. Adding the panel 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
2
frame.add(newPanel);
anotherPanel.add(newPanel);
1
2
| frame.add(newPanel); anotherPanel.add(newPanel); |
5. Customizing appearance
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
2
newPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Login Panel"
));
1
| newPanel.setBackground(Color.CYAN); |
1
| newPanel.setOpaque( false ); // make transparent background |
By default, the panel’s background is opaque.
1
| newPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); |
1
| newPanel.setBorder(BorderFactory.createEtchedBorder()); |
1
| newPanel.setBorder(BorderFactory.createLineBorder(Color.RED)); |
1
2
| newPanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Login Panel" )); |
6. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package
net.codejava.swing.jpanel;
import
java.awt.GridBagConstraints;
import
java.awt.GridBagLayout;
import
java.awt.Insets;
import
javax.swing.BorderFactory;
import
javax.swing.JButton;
import
javax.swing.JFrame;
import
javax.swing.JLabel;
import
javax.swing.JPanel;
import
javax.swing.JPasswordField;
import
javax.swing.JTextField;
import
javax.swing.SwingUtilities;
import
javax.swing.UIManager;
/**
* This program demonstrates how to use JPanel in Swing.
* @author www.codejava.net
*/
public
class
SwingJPanelDemo
extends
JFrame {
private
JLabel labelUsername =
new
JLabel(
"Enter username: "
);
private
JLabel labelPassword =
new
JLabel(
"Enter password: "
);
private
JTextField textUsername =
new
JTextField(
20
);
private
JPasswordField fieldPassword =
new
JPasswordField(
20
);
private
JButton buttonLogin =
new
JButton(
"Login"
);
public
SwingJPanelDemo() {
super
(
"JPanel Demo Program"
);
// create a new panel with GridBagLayout manager
JPanel newPanel =
new
JPanel(
new
GridBagLayout());
GridBagConstraints constraints =
new
GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets =
new
Insets(
10
,
10
,
10
,
10
);
// add components to the panel
constraints.gridx =
0
;
constraints.gridy =
0
;
newPanel.add(labelUsername, constraints);
constraints.gridx =
1
;
newPanel.add(textUsername, constraints);
constraints.gridx =
0
;
constraints.gridy =
1
;
newPanel.add(labelPassword, constraints);
constraints.gridx =
1
;
newPanel.add(fieldPassword, constraints);
constraints.gridx =
0
;
constraints.gridy =
2
;
constraints.gridwidth =
2
;
constraints.anchor = GridBagConstraints.CENTER;
newPanel.add(buttonLogin, constraints);
// set border for the panel
newPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Login Panel"
));
// add the panel to this frame
add(newPanel);
pack();
setLocationRelativeTo(
null
);
}
public
static
void
main(String[] args) {
// set look and feel to the system look and feel
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch
(Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(
new
Runnable() {
@Override
public
void
run() {
new
SwingJPanelDemo().setVisible(
true
);
}
});
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
| package net.codejava.swing.jpanel; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; /** * This program demonstrates how to use JPanel in Swing. * @author www.codejava.net */ public class SwingJPanelDemo extends JFrame { private JLabel labelUsername = new JLabel( "Enter username: " ); private JLabel labelPassword = new JLabel( "Enter password: " ); private JTextField textUsername = new JTextField( 20 ); private JPasswordField fieldPassword = new JPasswordField( 20 ); private JButton buttonLogin = new JButton( "Login" ); public SwingJPanelDemo() { super ( "JPanel Demo Program" ); // create a new panel with GridBagLayout manager JPanel newPanel = new JPanel( new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets( 10 , 10 , 10 , 10 ); // add components to the panel constraints.gridx = 0 ; constraints.gridy = 0 ; newPanel.add(labelUsername, constraints); constraints.gridx = 1 ; newPanel.add(textUsername, constraints); constraints.gridx = 0 ; constraints.gridy = 1 ; newPanel.add(labelPassword, constraints); constraints.gridx = 1 ; newPanel.add(fieldPassword, constraints); constraints.gridx = 0 ; constraints.gridy = 2 ; constraints.gridwidth = 2 ; constraints.anchor = GridBagConstraints.CENTER; newPanel.add(buttonLogin, constraints); // set border for the panel newPanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Login Panel" )); // add the panel to this frame add(newPanel); pack(); setLocationRelativeTo( null ); } public static void main(String[] args) { // set look and feel to the system look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { ex.printStackTrace(); } SwingUtilities.invokeLater( new Runnable() { @Override public void run() { new SwingJPanelDemo().setVisible( true ); } }); } } |
Other Java JPanel Example
Output:
Output:
No comments:
Post a Comment