stretched button in the gridLayout

15,833

Solution 1

You should refrain from setting the size yourself. You should select a proper LayoutManager that does the job for you.

(Unless you explicitly do setLayout(null) the sizes you set will be discarded and the current layout manager will assign new sizes to the components.)

You say that you're using a GridLayout. This layout is fairly "unflexible", and if you want the benefits of GridLayout but more flexibility, you could give GridBagLayout a try.

If you don't find a layout manager that suites your needs, don't be afraid of writing your own. (It's five relatively easy methods to implement.)

If you post a screen-shot of your current application, and an explanation on how you want it to look, we'll be able to help you further.

Some useful links

Solution 2

When you are using layout managers (like GridLayout) then calls to setSize() generally don't work, because the layout manager ultimately decides how to size and place each component in a container.

What you can do is call setPreferredSize(), setMaximumSize() and/or setMinimumSize(). Depending on the layout manager in use one or more of these requests (because that's really what they are) will be honoured. When you call frame.pack() it will try to size everything in the container (and subcontainers) to their preferred sizes.

So, in your case, calling myButton.setPreferredSize (10, 10); will probably work. However, it will still be resized if the container changes size. If you don't want that, there are other solutions I can post.

Solution 3

When aloobe seems to have a more general solution for you. I'd say the immediate solution would be to add the button to a JPanel, set the Layoutmanager a layout like GridLayout, or another LayoutManager, if you find another suits you better.

And add this panel to your original panel, in place of the button.

Share:
15,833
rookie
Author by

rookie

Updated on June 04, 2022

Comments

  • rookie
    rookie almost 2 years

    everyone, I have some problem with Java I created panel with five rows and one column, also I added button to the one of the rows, finally I added this panel to the frame, and I received button which is stretched to full frame, can I reduce the size of the button, I used

    myButton.setSize(10,10);
    

    but it doesn't seem to work, also I use

    frame.pack();
    

    may it be the problem, thanks in advance

  • Andrew Thompson
    Andrew Thompson about 13 years
    My term for that is a 'nested layout'. I could not imagine creating a workable GUI using any one layout (not even GrievousBodilyLayout, oh excuse me - GridBagLayout).