Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a gap around the edge of a Jbutton?

I want to leave the default border on my JButtons, but put empty space around them as well. I'm using a vertical BoxLayout.

  • I originally said nothing about the borders, and got single pixel LineBorders, which I want, but the buttons all butted up against each other.

  • I then tried button[i].setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)). Rather than adding blank space around the button, it made the buttons' areas expand. It also removed the LineBorder.

  • I then tried: button[i].setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(5, 5, 5, 5), button.getBorder()))

This gave me back the LineBorder, but rather than adding blank space outside the line, it just extended the buttons' areas beyond the line!

I realise I can add blank boxes to space my buttons out, but I want space on the sides of them as well, which is why I want to add an EmptyBorder. I'm new to Swing, so maybe there's an entirely better way of doing this that I don't know about :)

I'm using Jython, but the API should be the same as from Java.

like image 259
Cam Jackson Avatar asked Jul 29 '11 06:07

Cam Jackson


2 Answers

Conceptually, the "empty borders" you want to add are not really part of the button (for example, they should not be clickable).

This is actually a matter of layout, so you should probably check the documentation of the layout manager you are using. For example:

  • Some layout managers, such as FlowLayout, BorderLayout, or GridLayout, have hgap and vgap properties to specify the horizontal and vertical gaps between components.
  • With GridBagLayout you would set the insets of a GridBagConstraints object.
  • With BoxLayout you would add "rigid areas", "glue", and "fillers" (see the Box class).

And so on.

like image 182
Grodriguez Avatar answered Sep 28 '22 07:09

Grodriguez


I think it's simpler to add the button to a panel and set the empty border to the panel.

like image 33
StanislavL Avatar answered Sep 28 '22 07:09

StanislavL