Question

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

Was it helpful?

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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top