10

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.

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
PB_MLT
  • 834
  • 3
  • 13
  • 30

2 Answers2

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
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
  • Thank you, this hint was very useful! – Erick Robertson Jun 18 '15 at 21:20
  • 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