• Post Reply Bookmark Topic Watch Topic
  • New Topic

Consistent button size in FlowLayout panel  RSS feed

 
Colm Dickson
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all.



I have a JPanel that I have set to use



(NB: I am coding this manually and not using the IDE so I cannot visually make the buttons the same)

If I also have 3 buttons, initialised with labels such as "aa", "bbbb","ccccccc" then as I add each button to the panel, they will differ in size based on the length of the label.
The 3 buttons will appear one below another, left justified but different sizes of course. I have tried making the labels the same length by right padding with spaces but this does not work out so well. I have also tried setting the button size programattically but this does not work(is this due to the influence of the layout manager?). So, what is the best way to display the 3 buttons with different label lengths so that the buttons are the same length and width, provided the label lengths are not wildly different (using code only)?


Thanks very much.

Colm

 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not convinced about FlowLayout. How about GridLayout, which tends to make all components the same size?

I shall move you; we usually discuss that sort of thing on the Swing forum.
 
Fred Hamilton
Ranch Hand
Posts: 684
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was just going to say grid layout. The following document deals specifically with this exact topic.

http://java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/shortcourse.html
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FlowLayout is rarely a good layoutManager to use, but if you're doing this for self-learning,
the way to size them the same in a FlowLayout is to set their preferredSizes the same.

3 buttons, b1,b2,b3. b3 will be the largest, so

b1.setPreferredSize(b3.getPreferredSize());
b2.setPreferredSize(b3.getPreferredSize());
 
Colm Dickson
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help.

Very useful. I used the setPreferredSize method as I needed the JPanel to be of type FlowLayout()




Colm.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!