The Wayback Machine - https://web.archive.org/web/20241128132738/https://www.geeksforgeeks.org/java-swing-jpanel-with-examples/
Open In App

Java Swing – JPanel With Examples

Last Updated : 10 Nov, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JPanel, a part of the Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, however, it does not have a title bar.

Constructors of JPanel 

  1. JPanel(): creates a new panel with a flow layout
  2. JPanel(LayoutManager l): creates a new JPanel with specified layoutManager
  3. JPanel(boolean isDoubleBuffered): creates a new JPanel with a specified buffering strategy
  4. JPanel(LayoutManager l, boolean isDoubleBuffered): creates a new JPanel with specified layoutManager and a specified buffering strategy

Commonly used Functions of JPanel 

  1. add(Component c): Adds a component to a specified container
  2. setLayout(LayoutManager l): sets the layout of the container to the specified layout manager
  3. updateUI(): resets the UI property with a value from the current look and feel.
  4. setUI(PanelUI ui): sets the look and feel of an object that renders this component.
  5. getUI(): returns the look and feel object that renders this component.
  6. paramString(): returns a string representation of this JPanel.
  7. getUIClassID(): returns the name of the Look and feel class that renders this component.
  8. getAccessibleContext(): gets the AccessibleContext associated with this JPanel.

Let us take a sample program in order to illustrate the use of JPanel class by appending sequential execution snapshots of outputs justifying the below program sets as follows:

Example:

Java




// Java Program to Create a Simple JPanel
// and Adding Components to it
  
// Importing required classes
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
  
// Class 1
// Helper class extending JFrame class
class solution extends JFrame {
  
    // JFrame
    static JFrame f;
  
    // JButton
    static JButton b, b1, b2;
  
    // Label to display text
    static JLabel l;
  
    // Main class
    public static void main(String[] args)
    {
        // Creating a new frame to store text field and
        // button
        f = new JFrame("panel");
  
        // Creating a label to display text
        l = new JLabel("panel label");
  
        // Creating a new buttons
        b = new JButton("button1");
        b1 = new JButton("button2");
        b2 = new JButton("button3");
  
        // Creating a panel to add buttons
        JPanel p = new JPanel();
  
        // Adding buttons and textfield to panel
        // using add() method
        p.add(b);
        p.add(b1);
        p.add(b2);
        p.add(l);
  
        // setbackground of panel
        p.setBackground(Color.red);
  
        // Adding panel to frame
        f.add(p);
  
        // Setting the size of frame
        f.setSize(300, 300);
  
        f.show();
    }
}


Output: 

Example 2:

Java




// Java Program to Create a JPanel with a Border Layout
// and Adding Components to It
  
// Importing required classes
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
  
// Main class
// Extending JFrame class
class solution extends JFrame {
  
    // JFrame
    static JFrame f;
  
    // JButton
    static JButton b, b1, b2, b3;
  
    // Label to display text
    static JLabel l;
  
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a new frame to store text field and
        // button
        f = new JFrame("panel");
  
        // Creating a label to display text
        l = new JLabel("panel label");
  
        // Creating a new buttons
        b = new JButton("button1");
        b1 = new JButton("button2");
        b2 = new JButton("button3");
        b3 = new JButton("button4");
  
        // Creating a panel to add buttons
        // and a specific layout
        JPanel p = new JPanel(new BorderLayout());
  
        // Adding buttons and textfield to panel
        // using add() method
        p.add(b, BorderLayout.NORTH);
        p.add(b1, BorderLayout.SOUTH);
        p.add(b2, BorderLayout.EAST);
        p.add(b3, BorderLayout.WEST);
        p.add(l, BorderLayout.CENTER);
  
        // setbackground of panel
        p.setBackground(Color.red);
  
        // Adding panel to frame
        f.add(p);
  
        // Setting the size of frame
        f.setSize(300, 300);
  
        f.show();
    }
}


Output:

 Example 3:

Java




// Java Program to Create a JPanel with a Box layout
// and Adding components to it
  
// Importing required classes
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
  
// Main class
// Extending JFrame class
class solution extends JFrame {
  
    // JFrame
    static JFrame f;
  
    // JButton
    static JButton b, b1, b2, b3;
  
    // Label to display text
    static JLabel l;
  
    // Main drive method
    public static void main(String[] args)
    {
        // Creating a new frame to store text field and
        // button
        f = new JFrame("panel");
  
        // Creating a label to display text
        l = new JLabel("panel label");
  
        // Creating a new buttons
        b = new JButton("button1");
        b1 = new JButton("button2");
        b2 = new JButton("button3");
        b3 = new JButton("button4");
  
        // Creating a panel to add buttons and
        // textfield and a layout
        JPanel p = new JPanel();
  
        // Setting box layout
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
  
        // Adding buttons and textfield to panel
        p.add(b);
        p.add(b1);
        p.add(b2);
        p.add(b3);
        p.add(l);
  
        // Setting background of panel
        p.setBackground(Color.red);
  
        // Adding panel to frame
        f.add(p);
  
        // Setting the size of frame
        f.setSize(300, 300);
  
        f.show();
    }
}


Output:

Henceforth, we are successfully able to generate buttons in our panel. 

Note: In the previous Program, border layout and Box Layout are used. Different other layouts can be used to organize the components in a definite pattern, such as card layout, grid layout, etc. 



Similar Reads

Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java Swing | Internal Frame with examples
JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many features of a frame which includes displaying title, opening, closing, resizing, support for menu bar, etc. Constructors for JInternalFrame JInternalFrame() : creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with n
8 min read
Java Swing | JSplitPane with Examples
JSplitPane is a part of Java Swing. JSplitPane is used to divide only two components. JSplitPane is to use resize the components . By using the JSplitPane the user can manually resize the component till its minimum size . JSplitPane can be of two types, one is the vertical and horizontal splitpane Constructor of JSplitPane are: JSplitPane() : creat
6 min read
Java Swing | JComboBox with examples
JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer .Constructor of the JComboBox are: JComboBox() : creates a new empty JComboBox .
7 min read
Java Swing | JCheckBox with examples
JCheckBox is a part of Java Swing package . JCheckBox can be selected or deselected . It displays it state to the user . JCheckBox is an implementation to checkbox . JCheckBox inherits JToggleButton class. Constructor of the class are : JCheckBox() : creates a new checkbox with no text or icon JCheckBox(Icon i) : creates a new checkbox with the ico
5 min read
Java Swing | JDialog with examples
JDialog is a part Java swing package. The main purpose of the dialog is to add components to it. JDialog can be customized according to user need .Constructor of the class are: JDialog() : creates an empty dialog without any title or any specified ownerJDialog(Frame o) :creates an empty dialog with a specified frame as its ownerJDialog(Frame o, Str
5 min read
Java Swing | JWindow with examples
JWindow is a part of Java Swing and it can appear on any part of the users desktop. It is different from JFrame in the respect that JWindow does not have a title bar or window management buttons like minimize, maximize, and close, which JFrame has. JWindow can contain several components such as buttons and labels. Constructor of the class are: JWin
5 min read
Java Swing | JList with examples
JList is part of Java Swing package . JList is a component that displays a set of Objects and allows the user to select one or more items . JList inherits JComponent class. JList is a easy way to display an array of Vectors .Constructor for JList are : JList(): creates an empty blank listJList(E [ ] l) : creates an new list with the elements of the
4 min read
Java Swing | Popup and PopupFactory with examples
Popup and PopupFactory are a part of the Java Swing library. Popups are used when we want to display to the user a Component on the top of all the other Components in that particular containment hierarchy. PopupFactory is the class that is used to create popups. Popups have a very small life cycle, and generally are lightweight components having li
5 min read
Java Swing | JSeparator with examples
JSeparator is a part of Java Swing framework. It is used to create a dividing line between two components. More specifically, it is mainly used to create dividing lines between menu items in a JMenu. In JMenu or JPopupMenu addSeparartor function can also be used to create a separator. Constructor of the class are: separator(): Creates a new horizon
4 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java Swing | ScrollPaneLayout Class
The layout manager used by JScrollPane. JScrollPaneLayout is based on nine components: a viewport, two scrollbars, a row header, a column header, and four "corner" components. Constructor of the class: ScrollPaneLayout(): It is used to Construct a new ScrollPaneLayout. Commonly Used Methods: removeLayoutComponent(Component comp): Removes the specif
4 min read
Java Swing | JFileChooser
JFileChooser is a part of java Swing package. The java Swing package is part of JavaTM Foundation Classes(JFC) . JFC contains many features that help in building graphical user interface in java . Java Swing provides components such as buttons, panels, dialogs, etc . JFileChooser is a easy and an effective way to prompt the user to choose a file or
11 min read
Java Swing | JTextField
JTextField is a part of javax.swing package. The class JTextField is a component that allows editing of a single line of text. JTextField inherits the JTextComponent class and uses the interface SwingConstants.The constructor of the class are : JTextField() : constructor that creates a new TextFieldJTextField(int columns) : constructor that creates
5 min read
Java Swing | JProgressBar
JProgressBar is a part of Java Swing package. JProgressBar visually displays the progress of some specified task. JProgressBar shows the percentage of completion of specified task.The progress bar fills up as the task reaches it completion. In addition to show the percentage of completion of task, it can also display some text .Constructors of JPro
4 min read
JLabel | Java Swing
JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel can display text, image or both . JLabel is only a display of text or image and it cannot get focus . JLabel is inactive to input events such a mouse focus or keyboard focus. By default labels are vertically centered but the user can change the align
4 min read
Java Swing | JToolBar
JToolBar is a part of Java Swing package. JToolBar is an implementation of toolbar. The JToolBar is a group of commonly used components such as buttons or drop down menu. JToolBar can be dragged to different locations by the user Constructors of the class are: JToolBar() : creates a new toolbar with horizontal orientationJToolBar(int o) : creates a
6 min read
JRadioButton | Java Swing
We use the JRadioButton class to create a radio button. Radio button is use to select one option from multiple options. It is used in filling forms, online objective papers and quiz. We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We use "ButtonGroup" class to create a ButtonGroup and add radio button in
6 min read
Java Swing | ToolTip
We can add tooltip text to almost all the components of Java Swing by using the following method setToolTipText(String s). This method sets the tooltip of the component to the specified string s. When the cursor enters the boundary of that component a popup appears and text is displayed. Methods used: getToolTipText() : returns the tooltip text for
4 min read
Java Swing | JSlider
JSlider is a part of Java Swing package . JSlider is an implementation of slider. The Component allows the user to select a value by sliding the knob within the bounded value . The slider can show Major Tick marks and also the minor tick marks between two major tick marks, The knob can be positioned at only those points. Constructor of the class ar
6 min read
Java Swing | Simple Calculator
Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of Oracle's Java foundation classes . Java Swing is an API for providing graphical user interface elements to Java Programs.Swing was created to provide more powerful and flexible components than Java AWT (Abstract Window Toolkit).In this article we will us
4 min read
Java Swing | Creating a Toast Message
What are toast messages? And how to create them by using Java Swing? Toast Messages are a quick way of informing the user by short Pop-up messages that last for a short period of time and then disappear. Java Swing does not have an inbuilt class for toast message but toast message is a popular and an effective way to display auto-expiring message t
3 min read
Java Swing | JTable
The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form.Constructors in JTable: JTable(): A table is created with empty cells.JTable(int rows, int cols): Creates a table of size rows * col
2 min read
Java Swing | BevelBorder and SoftBevelBorder
BevelBorder and SoftBevelBorder are a part of javax.swing.Border package. This package contains different Border for Components. BevelBorder is an implementation of a simple two line bevel border. Bevel Border and Soft Bevel Border are almost same but Soft Bevel Border has softened corners.Constructor for the class BevelBorder: BevelBorder(int Type
7 min read
Java Swing | MatteBorder
MatteBorder is a class which is used to make a matte-like border of either a solid color or a tiled icon. It is a part of javax.swing.border package and contains different styles of Borders for Components. This class helps us to set an icon or a solid color as a border and the insets of the border can also be applied using this class.Constructor of
5 min read
Java Swing | JToggleButton Class
A JToggleButton is a two-state button. The two states are selected and unselected. The JRadioButton and JCheckBox classes are subclasses of this class. When the user presses the toggle button, it toggles between being pressed or unpressed. JToggleButton is used to select a choice from a list of possible choices. Buttons can be configured, and to so
4 min read
Java Swing | GroupLayout Class
GroupLayout is a LayoutManager that hierarchically group the components and arranges them in a Container. Grouping is done by using the instances of the Group class. It is generally used for developing a GUI ( Graphic User Interface) builders such as Matisse, the GUI builder provided with the NetBeans IDE. GroupLayout Class supports two types of gr
6 min read
Java Swing | JColorChooser Class
JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color. This class provides three levels of API: A static convenience method that shows a modal color-chooser dialog and returns the color selected by the user.A static convenience method for creating a color-chooser dialog where ActionListeners can be spec
5 min read
Difference between AWT and Swing in Java
Java is one of the most in-demand programming languages for developing a variety of applications. The popularity of Java can be attributed to its versatility as it can be used to design customized applications that are light and fast and serve a variety of purposes ranging from web services to android applications. Java is fast, reliable, and secur
2 min read
Student Grade Calculator using Java Swing
Consider the following scenario. We need to create a GUI based application which calculates grade of students according to marks obtained in 4 subjects. Below are the range of marks for different grades. MarksGrade>90%ABetween 85% - 90%BBetween 80% - 85%CBetween 70% - 80%DBetween 60% - 70%EBetween 50% - 60%Poor We will be using Netbeans to creat
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg