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

- 37,241
- 25
- 195
- 267

- 22,386
- 64
- 200
- 328
-
1As 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 Answers
setBorder(BorderFactory.createEmptyBorder(int top, int left, int bottom, int right));
And for more details you can read the documentation about BorderFactory

- 376
- 2
- 9

- 22,386
- 64
- 200
- 328
-
2Why did you mark your own answer as 'correct' when kleopatra had provided the answer more than 2 days ago? – Andrew Thompson May 05 '11 at 08:41
-
6@ Andrew Thompson this was the best answer i found recently,thus i updated the answers – Suhail Gupta May 05 '11 at 10:11
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

- 51,061
- 28
- 99
- 211
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

- 3,804
- 3
- 32
- 50
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

- 109,525
- 20
- 134
- 319