Swing: Borders

Swing provides various borders those have different look and size. You can add the border using setBorder() method for any component. JComponent provides this method for all available components. javax.swing.border package has various deferent types of borders.
You can create border through two ways:
The BorderFactory class creates any kind of border for you using static "factory" methods. Creating and setting a component's border, then, is simple:
    JLabel labelTwo = new JLabel("etched border.");
    labelTwo.setBorder(BorderFactory.createEtchedBorder(  ));
 
You can create the instance of border class directly.
 
JLabel labelTwo = new JLabel("raised etched border.");
labelTwo.setBorder( new EtchedBorder(EtchedBorder.RAISED) );

There are following border classes
BevelBorder
SoftBevelBorder
EmptyBorder
EtchedBorder
LineBorder
MatteBorder
TitledBorder
CompoundBorder


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class BordersDemo 
{
      public static void main(String[] args) {

        JFrame frame = new JFrame("BordersDemo");

        int center = SwingConstants.CENTER;
        JLabel labelOne = new JLabel("raised BevelBorder", center);
        labelOne.setBorder(
            BorderFactory.createBevelBorder(BevelBorder.RAISED));
        JLabel labelTwo = new JLabel("EtchedBorder", center);
        labelTwo.setBorder(BorderFactory.createEtchedBorder(  ));
        JLabel labelThree = new JLabel("MatteBorder", center);
        labelThree.setBorder(
            BorderFactory.createMatteBorder(10, 10, 10, 10, Color.pink));
        JLabel labelFour = new JLabel("TitledBorder", center);
        Border etch = BorderFactory.createEtchedBorder(  );
        labelFour.setBorder(
            BorderFactory.createTitledBorder(etch, "Title"));
        JLabel labelFive = new JLabel("TitledBorder", center);
        Border low = BorderFactory.createLoweredBevelBorder(  );
        labelFive.setBorder(
            BorderFactory.createTitledBorder(low, "Title",
            TitledBorder.RIGHT, TitledBorder.BOTTOM));
        JLabel labelSix = new JLabel("CompoundBorder", center);
        Border one = BorderFactory.createEtchedBorder(  );
        Border two =
            BorderFactory.createMatteBorder(4, 4, 4, 4, Color.blue);
        labelSix.setBorder(BorderFactory.createCompoundBorder(one, two));

       
        Container c = frame.getContentPane(  ); 
        c.setLayout(new GridLayout(3, 2,10,10));
        c.add(labelOne);
        c.add(labelTwo);
        c.add(labelThree);
        c.add(labelFour);
        c.add(labelFive);
        c.add(labelSix);

        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.pack(  );
        frame.setVisible(true);
      }
    }

No comments:

Popular Posts