Java Swing Tutorial - Java Swing JPanel








A JPanel is a container for other components. We can set its layout manager, border, and background color. JPanel groups related components.

Create JPanel

The following table lists the constructors for the JPanel Class.

IDConstructor/Description
1JPanel()
Creates a JPanel with FlowLayout and double buffering.
2JPanel(boolean isDoubleBuffered)
Creates a JPanel with FlowLayout and the specified double buffering flag.
3JPanel(LayoutManager layout)
Creates a JPanel with the specified layout manager and double buffering.
4JPanel(LayoutManager layout, boolean isDoubleBuffered)
Creates a JPanel with the specified layout manager and double buffering flag.

The following code shows how to create a JPanel with a BorderLayout and add buttons to it.

import java.awt.BorderLayout;
/* w w  w  .j  a va  2  s  .c o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel buttonPanel = new JPanel(new BorderLayout()); 
    JButton northButton = new JButton("North");
    JButton southButton = new JButton("South"); 
    JButton eastButton  = new JButton("East"); 
    JButton  westButton = new JButton("west");

    buttonPanel.add(northButton, BorderLayout.NORTH); 
    buttonPanel.add(southButton, BorderLayout.SOUTH); 
    buttonPanel.add(eastButton,  BorderLayout.EAST); 
    buttonPanel.add(westButton,  BorderLayout.WEST);

    frame.add(buttonPanel,  BorderLayout.CENTER);
     

    frame.pack();
    frame.setVisible(true);
  }
}




Using JPanel as a canvas

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
  public Main() {
  }/*from w  ww .  j  av a 2 s  .  c  o  m*/
  public void paintComponent(Graphics g) {
    int width = getWidth();
    int height = getHeight();
    g.setColor(Color.black);
    g.drawOval(0, 0, width, height);
  }
  public static void main(String args[]) {
    JFrame frame = new JFrame("Oval Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Main());
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}