JPanel Program in Java

 JPanel is a class in Java Swing that provides a container for organizing and grouping components. It is a lightweight component that can be added to other containers like JFrame or JDialog.

Here is an example program that demonstrates how to use a JPanel:

java

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JButton; 
import java.awt.BorderLayout; 
import java.awt.Color; 
public class JPanelExample extends JFrame 

private JPanel panel; 
private JButton button1, button2; 
public JPanelExample() 

super("JPanel Example"); 
 setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new JPanel(); panel.setBackground(Color.WHITE); getContentPane().add(panel, BorderLayout.CENTER); button1 = new JButton("Button 1"); 
 panel.add(button1); 
 button2 = new JButton("Button 2"); panel.add(button2); 
 setVisible(true); 
 } 
public static void main(String[] args)

new JPanelExample(); 
 } 
}

In this program, we create a new JFrame with a title "JPanel Example" and size of 300x200 pixels. We then set the default close operation to exit the program when the user clicks the close button.

Next, we create a new JPanel and set its background color to white. We add the panel to the center of the JFrame using the BorderLayout. We then create two new JButtons and add them to the panel.

Finally, we make the JFrame visible by calling setVisible(true).

When we run the program, we see a window with two buttons labeled "Button 1" and "Button 2" arranged in a vertical line on a white background. The buttons are contained within the JPanel, which is in turn contained within the JFrame.

This is just a simple example of how to use a JPanel. JPanels can be customized in many ways, such as setting a border, layout manager, or adding other components like text fields, labels, or images.

Comments

Popular posts from this blog

Cryptography API

Java Applet Overview

Vector in Java