I have a JButton that I would like to expand to fill the size of a JPanel that is holding it. I’ve tried doing this a few different ways, with no luck. Here are some attempts:
-
Manual size setting as recommended here – size of the button did not change.
panel = new JPanel(new CardLayout()); button = new JButton(); button.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE)); panel.add(button); -
Trying to use a
BorderLayoutto expand the button as hinted at here. Size did not change.panel = new JPanel(new BorderLayout()); button = new JButton(); panel.add(button, BorderLayout.CENTER);
I’m probably doing something incorrectly, so any help is much appreciated.
EDIT
Here is a summary of what resolved it. There are 2 things that worked
- Removing the LayoutManager (in the call to
new JPanel), which according to Oracle defaults to BorderLayout. - Adding the dimensions to the call as in the accepted answer (i.e.
new BorderLayout(0,0)).
Your second attempt should be working, but that does not mean your entire top level container will be filled by the
JPanelthat contains yourJButton. When there are no other components in aBorderLayoutcontainer, the center component will expand to fill the entire container.http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html
Can you post an image of what you’re seeing when you run your app? Here is a working example below. One thing worth noticing is that every container all the way up to the top
JFrameis also usingBorderLayout. It’s possible in your attempt that some upper level container is restricting the size of yourJPanel, and therefore also theJButtoninside.