6

I have two JButtons with texts "Ok" and "Cancel". I am using GridBagLayout to align them in a JDialog. I have set the anchor to GridBagConstraints.CENTER. Due to the difference in the number of characters in the texts "Ok" and "Cancel", the buttons are of different sizes. How do I align them correctly so that each of them have the same size. I tried the following but no avail.

okayButton.setSize(cancelButton.getSize());
Catalina Island
  • 7,027
  • 2
  • 23
  • 42
Kaushik Balasubramanain
  • 1,248
  • 6
  • 28
  • 42
  • 2
    just for emphasis: sizing/positioning the components is the job of the LayoutManager (which you already use, good!) - setSize in application code has (and is expected to and must have :-) _no_ effect – kleopatra Sep 13 '11 at 06:32

3 Answers3

1

Try setting the fill to GridBagConstraints.BOTH and give both buttons equal weight.

aioobe
  • 413,195
  • 112
  • 811
  • 826
1

GridBaglayout have got GridBagConstraints and in all cases accepts PreferredSize

examples here and here

mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

Instead of okayButton.setSize(cancelButton.getSize()); use okayButton.setPreferredSize(cancelButton.getPreferredSize());

Mohayemin
  • 3,841
  • 4
  • 25
  • 54
  • 1
    -1 no ... never-ever use setXXSize in application code (for some reasons, see http://stackoverflow.com/questions/7229226/avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swing) instead use a decent LayoutManager – kleopatra Sep 13 '11 at 07:34
  • By the way, should I remove answers those may mislead people? – Mohayemin Sep 16 '11 at 08:19