Widgets behaving strangely when using "setlayout(null)"

מןהזס picture מןהזס · Sep 6, 2012 · Viewed 19.1k times · Source

I'm doing the following call in my code:

...
setLayout(null);
...

I'm trying to place a button and a textfield by specifying their x and y coordinates.

The problem when I run the program (either with Eclipse or BlueJ) is that I need to run on the panel up to the position of the button and the textfield in order to see respectively the button and the textfield.

When I find the textfield, it is small. Only when I start writing it assumes the size I specified.

Does anyone know how to solve it?

Answer

lbalazscs picture lbalazscs · Sep 6, 2012
  1. Avoid setLayout (null), unless you have a very good reason for it. You can learn about layout managers here: http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

  2. If you still want to use a null layout, you have to set the width and height of the component, not just its x and y position (see the setSize method).

From the link mentioned above:

Although we strongly recommend that you use layout managers, you can perform layout without them. By setting a container's layout property to null, you make the container use no layout manager. With this strategy, called absolute positioning, you must specify the size and position of every component within that container. One drawback of absolute positioning is that it does not adjust well when the top-level container is resized. It also does not adjust well to differences between users and systems, such as different font sizes and locales.