Tom
Tom

Reputation: 441

How to set size of JTextField in pixels

Hey I was just wondering if there is a way to set JTextField width for example 50% of the screen size. I know how to get the dimensions of screen just JTextField sets it to number of characters not pixels

textfield = new JTextField("Way hello there", 20);

is there a way to do this ?

Upvotes: 1

Views: 14253

Answers (2)

Reimeus
Reimeus

Reputation: 159754

Setting the size of JTextField in pixels leads you down the path of using absolute positioning which is generally not advisable. From Doing Without a Layout Manager

Although it is possible to do without a layout manager, you should use a layout manager if at all possible. Layout managers also can be reused easily by other containers, as well as other programs.

Have a look at the functionality offered by existing layout managers and avoid using the setXXXSize() component methods. For example, GridLayout ( or even GridBagLayout) can be used to size a JTextField width to 50% of a frame client area.

Upvotes: 2

Viral Patel
Viral Patel

Reputation: 8601

You may use setSize() method to set the size of JTextField component.

public void setSize(int width,
                    int height)

Resizes this component so that it has width width and height height. Parameters: width - the new width of this component in pixels height - the new height of this component in pixels

Javadoc: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html#setSize(int, int)

Edit: Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:

Also use setPreferredSize instead of setSize.

Upvotes: -1

Related Questions