javacodex.com
Java Examples
Java Examples
memu home questions

JPanel

A JPanel is a container that can contain other components. You can set its layout manager, border, and background color. Typically, you use a JPanel to group related components and add it to another container such as to a content pane of a JFrame. Note that a JPanel is a container, but not a top-level container, whereas a JFrame is a top-level container. Therefore, you cannot display a JPanel by itself in a Swing application, unless you add it to a top-level container. Sometimes, a JPanel is inserted between two components to create a gap. You can also use a JPanel as a canvas for drawing such as for drawing lines, rectangles, circles, etc.

Source: (JPanelExample.java)

import javax.swing.*;
import java.awt.*;
 
public class JPanelExample {
 
  public static void main(String[] arguments) {
 
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    JButton b1 = new JButton("B1");
 
    // add a JButton to the JPanel.
    panel.add(b1);
 
 
 
    // main window
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JPanel Example");
    frame.setSize(300,150);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    // add the Jpanel to the main window
    frame.add(panel); 
 
    frame.setVisible(true);
 
  }
}
 

Output:

$ java JPanelExample
Output



Contact: javacodex@yahoo.com