5

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.setIcon(icon);
pdt.setText("blah blah");
pdt.setIconTextGap(5);
pdt.setBorder(border1);
....

What does border1 do here.

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

Sachith Muhandiram
  • 2,819
  • 10
  • 45
  • 94
developer3
  • 75
  • 2
  • 9
  • 1
    Have you tried checking out the [documentation](https://docs.oracle.com/javase/7/docs/api/javax/swing/border/EmptyBorder.html) for `EmptyBoarder`? – Vince Nov 23 '16 at 08:21
  • EmptyBorders are as the name implies, a border without any content, basically all it does is add an invisible border around the component its applied to. – Chains Nov 23 '16 at 09:18
  • (1-) `Can I use EmptyBorder to give spacing between a set of controls in FlowLayout?` - What kind of question is this? Try it and see what happens!!! – camickr Nov 23 '16 at 15:56

1 Answers1

5

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");
    firstLabel.setBorder(border1);

    JLabel secondLabel = new JLabel("SECOND");

    displayPanel.add(firstLabel);
    displayPanel.add(secondLabel);
    setContentPane(displayPanel);

    pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

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

}
Chains
  • 456
  • 4
  • 14