JPanel and BorderFactory

The JPanel class defines something like a physical panel that you can use as a container to group a set of components. However, you can also place a component to which you want to add a border in a JPanel container, and add the border to the JPanel object.

You decorate the panel with a border by calling its setBorder() method. If you like, add a title to your border by passing your border to BorderFactory.createTitleBorder

Program

1

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.FlowLayout;

class Frame extends JFrame {
 
    Frame()
    {
        setTitle("JPanel");
        setLayout(new FlowLayout());
        setJPanelandComponents();
        setSize(700,200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    private void setJPanelandComponents()
    {
        JPanel jp = new JPanel();
        jp.setBorder(BorderFactory.createTitledBorder("JPanel Title"));
        for(int i=0;i<5;i++)
        {
            jp.add(new JButton("JButton "+i));
        }
        add(jp);
    }
}

public class Javaapp {
 
    public static void main(String[] args) {
     
       Frame fr = new Frame();
    }
}

Leave a Comment