6

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.

Grodriguez
  • 21,501
  • 10
  • 63
  • 107
Cam Jackson
  • 11,860
  • 8
  • 45
  • 78

2 Answers2

5

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:

And so on.

Grodriguez
  • 21,501
  • 10
  • 63
  • 107
3

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

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • This could work too. The border on the panel would then be an empty inside an etched, inside a title, inside an empty (space on the outside of the panel). Am I 'Doing It Wrong' if I have four layers of nesting on my borders? – Cam Jackson Jul 29 '11 at 06:52
  • Multiple layers is ok. I would even create a custom component MyBorderedButton extends JPanel and use it instead of button where it's necessary. – StanislavL Jul 29 '11 at 06:55
  • @StanislavL: I find it confusing to have a XXXButton subclass which is actually a JPanel (and not a subclass of Button). For example, would attach an action listener to your MyBorderedButton, or to the Button inside? – Grodriguez Jul 29 '11 at 07:15
  • You can add such a method and call delegate button's method. – StanislavL Jul 29 '11 at 07:39
  • 1
    Of course -- but this was just an example. If you use other JButton functions and features you might end up replicating a large part of the JButton API in the MyBorderedButton class. – Grodriguez Jul 29 '11 at 08:34
  • +1 The [`setBorder()`](http://download.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#setBorder%28javax.swing.border.Border%29) API suggests just this approach. – trashgod Jul 29 '11 at 10:42