What is JPanel - Java Swing

Java examples for Swing:JPanel

Introduction

A JPanel is a container for other components.

You can set its layout manager, border, and background color to a JPanel.

JPanel is used to group related components and add it to another container.

The default layout manager for a JPanel is FlowLayout.

Constructors for the JPanel Class

Constructor Description
JPanel() Creates a JPanel with FlowLayout and double buffering.
JPanel(boolean isDoubleBuffered) Creates a JPanel with FlowLayout and the specified double buffering flag.
JPanel(LayoutManager layout) Creates a JPanel with the specified layout manager and double buffering.
JPanel(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 four buttons to it.

Demo Code

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {

  public Main() {
    super("JButton Clicked Counter");

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    // Create a JPanel and four buttons
    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");

    // Add buttons to the JPanel
    buttonPanel.add(northButton, BorderLayout.NORTH);
    buttonPanel.add(southButton, BorderLayout.SOUTH);
    buttonPanel.add(eastButton, BorderLayout.EAST);
    buttonPanel.add(westButton, BorderLayout.WEST);

    add(buttonPanel, BorderLayout.SOUTH);
  }/*from w w  w  .java2s. c  o m*/

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials