Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

jbutton layout question  RSS feed

krillian konstatos
Ranch Hand
Posts: 49
Java Netbeans IDE PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5167
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!