File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes jbutton layout question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "jbutton layout question" Watch "jbutton layout question" New topic

jbutton layout question

krillian konstatos
Ranch Hand

Joined: Jan 03, 2011
Posts: 49

hi, everyone!

I am using GridBagLayout a lot as my favorite layoutmanager and often i have had the need to set
equal margin values for JButton objects in other words i want the space from the left and the right
edges of the text to be of the same width. I know it might be easier to use other layoutmanagers
but for now i am confused with this issue. I have an example of code to highlight my problem in the
space below this text:

In the code snippet above its obvious that the "view titles" button object will always be larger than
the button object labeled "Save". How can i set the margin with for the save button in the code
above so that this button will stretch out to the same width as the "view titles" button? I have not
experimented that much with the FontMetrics class but i can imagine that its there that the solution
to my problem resides or maybe i am completely missing something big here and should stick to
another layoutmanager for this purpose ... i just need some advice on how to see things clearer
around this problem.

Darryl Burke

Joined: May 03, 2008
Posts: 5115

One way is to add both the buttons to a JPanel with a GridLayout(1, 2, hgap, 0) and add that JPanel to your outer panel which has a GridBagLayout, with colspan = 2 if required.

Another way, but not recommended, is to obtain the preferredSize of each button and set both to the same value (the wider of the two).

To get better help sooner, post a SSCCE (Short, Self Contained, Compilable and Executable) example, without all the irrelevant tooltip/action/mnemonic stuff, that demonstrates the problem.

luck, db
There are no new questions, but there may be new answers.
I agree. Here's the link:
subject: jbutton layout question
It's not a secret anymore!