I use multiple components that has a border painted. Is there any easy way to add a margin to the component so that the borders aren't painted so close to eachother?
+1
A:
This is typically done using your layout manager. For example, if you are using GridBagLayout
, you would set insets
on the GridBagConstraint
object to the desired value.
Another option is to use the Box
object and add a horizontal or vertical struct. See javadoc for Box.createVerticalStrut( int width )
and the similar createHorizontalStrut
.
Alex B
2010-05-21 15:15:50
Yes, I could use `Box` but the code will be so ugly if I have many Box-margins...
Jonas
2010-05-21 15:20:16
Have you tried using insets? What layout are you currently using? How complicated is your display?
Alex B
2010-05-21 15:22:36
@Alex B: The layout is complex, it is a Invoice class that implements `Printable`, so I use many different layoutmanagers, `SpringLayout`, `BorderLayout`, `BoxLayout` and so on... I will try to use Insets, thanks.
Jonas
2010-05-21 15:28:51
+1
A:
Another way to get what you want is to:
- get the current
Border
of your component - if
null
, set anEmptyBorder
for your component - if not
null
, create a newCompoundBorder
(with anEmptyBorder
and the currentBorder
of the component) and set it for the component
In code, that should look like that (sorry I haven't tested it):
Border current = component.getBorder();
Border empty = new EmptyBorder(top, left, bottom right);
if (current == null)
{
component.setBorder(empty);
}
else
{
component.setBorder(new CompoundBorder(empty, current));
}
Where:
- component is the Swing component to which you want to add a margin
- top, left, bottom, right are the pixels amounts you want to add around your component
Note that this method might have an impact (size, alignment) on the form layout, depending on the LayoutManager
you are using. But I think it is worth trying.
jfpoilpret
2010-05-22 01:15:07