permaculture playing cards
The moose likes Swing / AWT / SWT and the fly likes JTextField preferred size Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTextField preferred size" Watch "JTextField preferred size" New topic

JTextField preferred size

Miklos Szeles
Ranch Hand

Joined: Oct 21, 2008
Posts: 142
I have a custom component, and I would like to set it's preferred height to the height of a JTextField. One way is to simply print out the preferred height of JTextField and use that number everywhere. Since I think this value not a constant(depend on platform,...) it not looks a good solution. Another possibilty is to create a JTextField at runtime and use it's height. That not sounds good also.
What is the proper way to achieve what I want?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20131

In one of my utility classes I have the following line:
I create one JTextField, retrieve its preferred size, retrieve that size's height, and both the size (Dimension) and the JTextField are eligible for garbage collection immediately. What's the problem with that?

Of course this will cause problems if you change the UI after retrieving the height, but you could make the field private and non-final with a method for updating the field.

How To Ask Questions How To Answer Questions
Miklos Szeles
Ranch Hand

Joined: Oct 21, 2008
Posts: 142
Thanks Rob.
I agree. Here's the link:
subject: JTextField preferred size
jQuery in Action, 3rd edition