Search code examples
javaswingjbuttonlayout-managergridbaglayout

stretched button in the gridLayout


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


Solution

  • 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