16

What is the method to set horizontal and vertical margins in a panel? (The same we have in html style="margins:30px")

Cœur
  • 37,241
  • 25
  • 195
  • 267
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • 1
    As others have mentioned, you should just use a Border (there is an EmptyBorder class in Swing to just do that). However, I would not recommend hard-coding the size of margins in a panel, especially using pixels (which size can change A LOT depending on the resolution of monitors). It is preferrable to use javax.swing.LayoutStyle to calculate the right margins. Or better, use a LayoutManager that does it for you. – jfpoilpret May 02 '11 at 08:23

5 Answers5

35

setBorder(BorderFactory.createEmptyBorder(int top, int left, int bottom, int right));

And for more details you can read the documentation about BorderFactory

John
  • 376
  • 2
  • 9
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
6

Don't know html, so just guessing on possible equivalents :-)

  • to set some space between a component's bounding rectangle and its content, the property to set is its Border
  • the spacing between the different components in a container is controlled by the LayoutManager (already mentioned). Depends on the concrete implementation how fine-grained that's configurable
kleopatra
  • 51,061
  • 28
  • 99
  • 211
0

Use a BorderLayout for your JPanel.

Heisenbug
  • 38,762
  • 28
  • 132
  • 190
0

That depends highly on the kind of Panel you are using. If this refers to swing you could put a Gridbaglayout on it and specify Insets like in this example

Hons
  • 3,804
  • 3
  • 32
  • 50
0

for create basic "Gap" between JComponents by using LayoutManagers Laying Out Components Within a Container

BorderLayout(int horizontalGap, int verticalGap)

GridLayout(int rows, int cols, int hgap, int vgap)

for most complex GUI you have to

1/ multiplayed JPanels (with different LayoutManager for each of JPanel too)

2/ by using How to Use GridBagLayout (by multiplayed JPanels with different LayoutManegars for each JPanel ...)

3/ use some Custom LayoutManager

mKorbel
  • 109,525
  • 20
  • 134
  • 319