JPanel,Color,setBackground,setBorder,createLineBorder,createMatteBorder

Border is the Swing interface that encapsulates a border. You can obtain a border by calling one of the factory methods defined by the BorderFactory class. The one used in the program is createLineBorder( ), which creates a simple line border. It is shown here:

static Border createLineBorder(Color clr, int width)

Here, clr specifies the color of the border and width specifies its width in pixels.

createMatteBorder(int top,
                                    int left,
                                    int bottom,
                                    int right,
                                    Color matteColor)

Creates a matte border with the specified insets and color.

Parameters:

top –                    the top inset of the border
left –                    the left inset of the border
bottom –             the bottom inset of the border
right –                 the right inset of the border
matteColor –      the color rendered for the border

setBackground(Color aColor) : Sets the background color to aColor. The background color is the color used for the basic component. You must use a different color from the background when you draw if you want what you have drawn to be visible.

Program

1

 

 

 

Program Source

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

class Frame extends JFrame {
   
    Frame()
    {
        setTitle("JPanel");
        setLayout(new FlowLayout());
        setJPanelOne();
        setJPanelTwo();
        setJPanelThree();
        setSize(700,250);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    private void setJPanelOne()
    {
        JPanel jp = new JPanel();
        jp.setBorder(BorderFactory.createLineBorder(Color.RED,3));
        for(int i=0;i<5;i++)
        {
            jp.add(new JButton("JButton "+i));
        }
        add(jp);
    }
    
    private void setJPanelTwo()
    {
        JPanel jp = new JPanel();
        jp.setBackground(Color.BLACK);
        jp.setBorder(BorderFactory.createLineBorder(Color.MAGENTA,3));
        for(int i=0;i<5;i++)
        {
            jp.add(new JButton("JButton "+i));
        }
        add(jp);
    }
    
    private void setJPanelThree()
    {
        JPanel jp = new JPanel();
        jp.setBackground(Color.LIGHT_GRAY);
        jp.setBorder(BorderFactory.createMatteBorder(20,20,20,20,Color.YELLOW));
        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