by Dinesh Thakur Category: Swing

A panel in swing is similar to Panel in AWT, is a lightweight container that is designed to group a set of components, including other panels. It is visually represented as window that does not contain a title bar, menu bar or border. It is simplest of all the containers. Its default layout manager is FlowLayout.

Panels are represented by objects created from JPanel class by calling the constructor.

public JPanel ()

After the panel has been created, other components can be added to JPanel object by calling its add (component) method inherited from the Container class. The following code fragment demonstrates creating a panel and adding two buttons to it.

JPanel p = new JPanel();

p. add (new JButton ("OK")) ;

p. add (new JButton ("Cancel") ) ;

Using panels, you can design complex GUls.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class JPanelExample extends JFrame
    JPanel panel1,panel2 ;
    JTextField txtData;
    JButton[] btnData = new JButton[12];
        panel1=new JPanel();
        txtData = new JTextField(20);
        panel2=new JPanel(new GridLayout(3,4));
        for(int i=0;i<=9;i++)
            btnData[i]=new JButton(""+i);
 class JPanelJavaExample
      public static void main(String[]  args)
          JPanelExample frame = new JPanelExample();
          frame.setTitle("JPanel Java Example");

JPanel in Java Swing Example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles