Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using Gridbag to set sizes of textfields

 
B. Smith
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I run the code below as a card on a non-descript cardLayout, I get something similar to what you see in the attachment.

Instead, I want all of the boxes to be the same size: large enough to hold the number "255", but no larger.

I was tempted to use the setMaximumSize and setMinimumSize, but I heard recently that those operations should be avoided, and that you could get the same functionality using the layoutManager itself. How would I change my code below to set the size of my textboxes without using those methods?

Thanks a ton!



cardLayout.png
[Thumbnail for cardLayout.png]
What I see when I run similar code.
 
Rob Camick
Ranch Hand
Posts: 2616
9
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The GridBagLayout will respect the preferred size of a component. For a JTextField you need to suggest what the preferred size should be by using:




The text field will now be sized to hold "WWW", which will be a little larger than "999", but that is the best you can do with the default JTextField.

If you want a more precise sizing then you would need to overrid the getPreferredSize() method of JTextField and provide your own calculation.
 
B. Smith
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it's good enough for you, it's good enough for me. Thanks a ton! Have a good day!
 
Darryl Burke
Bartender
Posts: 5148
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Camick wrote:If you want a more precise sizing then you would need to overrid the getPreferredSize() method of JTextField and provide your own calculation.

... or set a monospaced Font.
 
Rob Camick
Ranch Hand
Posts: 2616
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Darryl Burke wrote:... or set a monospaced Font.


Good point!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic