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
  • 6,905
  • 2
  • 22
  • 41
Kaushik Balasubramanain
  • 1,218
  • 6
  • 28
  • 38
  • 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
  • 399,198
  • 105
  • 792
  • 807
1

GridBaglayout have got GridBagConstraints and in all cases accepts PreferredSize

examples here and here

mKorbel
  • 109,107
  • 18
  • 130
  • 305
1

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

Mohayemin
  • 3,791
  • 4
  • 26
  • 52
  • 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