developer3 developer3 - 1 year ago 130
Java Question

What exactly does an EmptyBorder do?

I'm trying to understand java swing code. I see a piece of code using EmptyBorder in it, but I do not understand what it is doing. I tried to comment that part and run without emptyborder applied, but it doesn't really show any difference to me. Or am I just missing out some minute change in UI?

The code:

EmptyBorder border1 = new EmptyBorder(3, 0, 6, 550);
JLabel pdt = new JLabel();
pdt.setText("blah blah");

What does border1 do here.

Can I use EmptyBorder to give spacing between a set of controls in FlowLayout?

Answer Source

As i mentioned in my comment, it just adds an transparent border around the components its added to, sometimes the effect can be hard to see, depending on the layout manager you use, so ill include some pictures of it in use on a flow layout (very easy to see the effect on a flow layout):

here is the flow layout with no added border:

Flow layout no empty border

and here is the flow layout with the left and right of the border set to 100 and 300 respectively, and the border is applied to the first label. flow layout with border applied to a label

and finally here is some code for you to test out how things change:

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class EmptyBorderShowCase extends JFrame{

private static final long serialVersionUID = 1L;

public EmptyBorderShowCase(){
    JPanel displayPanel = new JPanel(new FlowLayout());
    final int BOTTOM = 0;
    final int LEFT = 100;
    final int RIGHT = 300;
    final int TOP = 0;
    EmptyBorder border1 = new EmptyBorder(TOP, LEFT, BOTTOM,RIGHT );

    JLabel firstLabel = new JLabel("FIRST");

    JLabel secondLabel = new JLabel("SECOND");



public static void main(String[]args){
    new EmptyBorderShowCase();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download