JPanel in Java with Example Using NetBeans
JPanel in Java:
The javax class.swing.JPanel is the default container for all controls. It is often used to group related controls. A JPanel usually forms the basis for graphics programming. Depending on the intended use, either further containers are added or, in the case of rather smaller applications, the control elements are placed directly on them. A JPanel is not limited to a certain number of elements it can hold.
JPanel Constructor:
constructor | description |
JPanel() | The default constructor creates a JPanel object with a default layout ( FlowLayout ) |
JPanel(LayoutManager layout) | You can pass a specific layout to this constructor. |
First, let’s look at two constructors that are important:
In the example below we add a JPanel to the dialog. We change the background color of this JPane l so that this panel is also visible. Without a different background color, it would match the background color of the dialog and no difference would be discernible.
Example: How to create a window using JPanel in java:
package com.mycompany.guiexamples; import java.awt.Color ; import javax.swing.JDialog ; import javax.swing.JPanel ; /** * * @author Fawadkhan */ public class Jpanel { public static void main ( String[ ] args ) { // creating object JDialog Dialog = new JDialog( ) ; Dialog.setTitle ("Testing JPanel") ; Dialog.setSize ( 400 , 300 ) ; JPanel panel = new JPanel( ) ; //Here we set the background color of our JPanel to green panel.setBackground(Color.green) ; Dialog.add( panel); // Here we add our JPanel to our dialog Dialog.setVisible( true ); // We display our dialog } }
In the above example, we create a JPanel object using the default constructor. Then we set the background color of our JPanel to green.Â
If you run the above Java source code, you will get the following picture:
Programming explanation:
First I import the required java classes using the import statement
import java.awt.Color ; import javax.swing.JDialog ; import javax.swing.JPanel ;
then I create the object for the JDialog and set the title and size of the dialog box
JDialog Dialog = new JDialog( ) ; Dialog.setTitle ("Testing JPanel") ; Dialog.setSize ( 400 , 300 ) ;
then I create the object for the JPanel
JPanel panel = new JPanel( ) ;
Here I set the background color of our JPanel to green
panel.setBackground(Color.green) ;
then I added our JPanel to our dialog
Dialog.add( panel);
This statement is used to display the dialog box
Dialog.setVisible( true );