Ahmed Nabil
Ahmed Nabil

Reputation: 41

SetLayout Function main purpose

 public void init_numSolvers() {
    for (x = 0; x < 9; x++) {
        n++;
        num[x] = new Button("" + n);
        add(num[x]);
        num[x].setBounds(num_x, num_y, 40, 40);
        setLayout(null);
        num_x += 40;
    }

why setBounds() function doesn't work without setLayout(null) i just want to understand the main purpose of setLayout(null) function

Upvotes: 1

Views: 27327

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You will want to read the tutorials and the API as they clearly spell out what setBounds and setLayout does, but briefly:

  • The setLayout(...) method allows you to set the layout of the container, often a JPanel, to say FlowLayout, BorderLayout, GridLayout, null layout, or whatever layout desired. The layout manager helps lay out the components held by this container.
  • The setBounds(...) method is used to set the location and size of a single component, and is only useful if null layout is used by the container that holds this component.
  • When you set a layout to null, you tell the container that it is using no layout at all, and so you the programmer are thus completely responsible for setting all the sizes and positions of components that are added to this container.
  • Having said this, you should strive to avoid using null layouts and setBounds(...). While to a newbie Swing programmer, this may seem the easiest way to create complex layouts, when using them you create GUI's that might look good on one platform only. More importantly, they create GUI's that are nearly impossible to maintain and upgrade without causing subtle bugs. Just don't use them if at all possible.
  • Please read the official layout manager tutorials on this as it is well explained there.

Note that your code repeatedly sets the container's layout to null within the for loop. I have no idea why it does this repeatedly since you only need to and want to set a container's layout once.

Upvotes: 6

Related Questions