Java Swing Tutorial - Java JPanel() Constructor








Syntax

JPanel() constructor from JPanel has the following syntax.

public JPanel()

Example

In the following code shows how to use JPanel.JPanel() constructor.

import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
//from  www .  j  a  v a2 s  .  c  om
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel buttonPanel = new JPanel();
    buttonPanel.addContainerListener(new ContainerListener() {
      public void componentAdded(ContainerEvent e) {
        displayMessage(" added to ", e);
      }
      public void componentRemoved(ContainerEvent e) {
        displayMessage(" removed from ", e);
      }
      void displayMessage(String action, ContainerEvent e) {
        System.out.println(((JButton) e.getChild()).getText() + " was" + action
            + e.getContainer().getClass().getName());
      }
    });
    buttonPanel.add(new JButton("A"));

    frame.add(buttonPanel);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }

}