File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes Using Gridbag to set sizes of textfields Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Using Gridbag to set sizes of textfields" Watch "Using Gridbag to set sizes of textfields" New topic
Author

Using Gridbag to set sizes of textfields

B. Smith
Greenhorn

Joined: Oct 03, 2011
Posts: 8
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]

Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2182
    
    7
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

Joined: Oct 03, 2011
Posts: 8
If it's good enough for you, it's good enough for me. Thanks a ton! Have a good day!
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4541
    
    5

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.


luck, db
There are no new questions, but there may be new answers.
Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2182
    
    7
Darryl Burke wrote:... or set a monospaced Font.


Good point!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using Gridbag to set sizes of textfields