1

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 ?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Tom
  • 421
  • 3
  • 6
  • 12
  • 2
    forgot about set coordinates in pixels, have to use proper LayoutManger, there are a two-tree LayoutManagers that can do that by default – mKorbel Dec 12 '12 at 21:27

2 Answers2

2

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.

Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276
-1

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.

Viral Patel
  • 8,506
  • 3
  • 32
  • 29
  • hmm tried this it doesn't seem to change the size. It is still the width of the text inside the text field. – Tom Dec 12 '12 at 21:30
  • 1
    Never, ever, use set[Preferred|Minimum|Maximum]Size. http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi – ignis Dec 12 '12 at 21:37