Java: cannot get JButton to be horizontally dense around text

I have a JButton that is much wider than the text that I inserted into it. I researched this, and I continue to find that I'm using Jbutton.setMargin(new Insets(0,0,0,0)); But that just doesn't work. In addition, setMaximumSize has no effect, although if I also set the minimum size, it changes the size of the button. But I do not want to set the size manually. I just want it to be less wide. What am I missing?

Here is my code for creating the button:

 plusminus = new JButton("+"); plusminus.setMargin(new Insets(0,0,0,0)); 

And here is what it looks like:

plus button

Thanks.

+4
source share
2 answers

I manually create my GUI. In this case, the layout is GroupLayout

Then this may be part of your problem. The size of your JButton is limited by the location of the container that holds it. One possible solution if you absolutely must use GroupLayout (which I hate by the way) is to place the JButton inside a JPanel that uses FlowLayout or some other layout that allows flexible size components, and put that JPanel in a container which is currently holding the button. Beware if your button is larger than JPanel.

+4
source

In the early bird I tried negative left and right inserts, and it worked incredibly. I then did not need a mess with min / max / prefix sizes. Btw my buttons are in the same JTable column.

+1
source

All Articles