Is it possible to make a JButton
take exactly the size of its text? Since by default, a JButton
will have a small amount of padding (both horizontal and vertical) around its text. I would like to remove that padding.
Asked
Active
Viewed 1.1k times
10

Erick Robertson
- 32,125
- 13
- 69
- 98

PB_MLT
- 834
- 3
- 13
- 30
2 Answers
13
JButton
has a border by default, you can remove it:
button.setBorder(null);
If you want to keep the border, reduce the margin (see Eugenes answer)

Community
- 1
- 1

Peter Lang
- 54,264
- 27
- 148
- 161
-
Thanks, and sorry for asking such a simple question. – PB_MLT Apr 26 '10 at 10:29
-
thank you, was going nuts trying to find where the damn padding was being set. – Gubatron Jun 07 '13 at 01:21
-
2-1 This answer removes the border. That's not what OP asked for. See the other answer to clear the margins without removing the border. – Erick Robertson Jun 18 '15 at 21:19
-
It is interesting that setting `btn.setBorderPainted(false)` does not do the same. You'd think it would. – Hunter S Nov 09 '15 at 15:43
12
Clear out the margins in the button with setMargin
.
Removing the border has the side-effect of removing the border. If you only want to clear out the margins, use the setMargin
method to set the margins all to zero.
button.setMargin(new Insets(0,0,0,0));

Erick Robertson
- 32,125
- 13
- 69
- 98

Eugene Ryzhikov
- 17,131
- 3
- 38
- 60
-
-
On my system I measured 16 pixels of horizontal padding left and right of the text before using this approach and 15 pixels after. There seems to be something else adding padding other than the button. Maybe the label the button creates for itself? I think the solution depends on the L&F and the system. I'm on macOS Big Sur using the default L&F and JDK 11. – Jason Apr 27 '21 at 14:39