Java JPanel

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java JPanel

The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class.

It doesn't have title bar.

JPanel class declaration

  1. public class JPanel extends JComponent implements Accessible  

Commonly used Constructors:

Constructor

Description

JPanel()

It is used to create a new JPanel with a double buffer and a flow layout.

JPanel(boolean isDoubleBuffered)

It is used to create a new JPanel with FlowLayout and the specified buffering strategy.

JPanel(LayoutManager layout)

It is used to create a new JPanel with the specified layout manager.

Java JPanel Example

  1. import java.awt.*;  
  2. import javax.swing.*;  
  3. public class PanelExample {  
  4.      PanelExample()  
  5.         {  
  6.         JFrame f= new JFrame("Panel Example");    
  7.         JPanel panel=new JPanel();  
  8.         panel.setBounds(40,80,200,200);    
  9.         panel.setBackground(Color.gray);  
  10.         JButton b1=new JButton("Button 1");     
  11.         b1.setBounds(50,100,80,30);    
  12.         b1.setBackground(Color.yellow);   
  13.         JButton b2=new JButton("Button 2");   
  14.         b2.setBounds(100,100,80,30);    
  15.         b2.setBackground(Color.green);   
  16.         panel.add(b1); panel.add(b2);  
  17.         f.add(panel);  
  18.                 f.setSize(400,400);    
  19.                 f.setLayout(null);    
  20.                 f.setVisible(true);    
  21.         }  
  22.         public static void main(String args[])  
  23.         {  
  24.         new PanelExample();  
  25.         }  
  26.     }  

Output:

Java Jpanel 1