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 BorderLayout
to 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
new JPanel
), which according to Oracle defaults to BorderLayout.new BorderLayout(0,0)
). For example, class JButton in swing API is a button component and provides the functionality of a button. One or more components form a group and this group can be placed in a “Container”.
The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class.
By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.
You may add a label in the first and a JPanel in the second column. The JPanel will resize to cover the enter cell. Then you add a button into that JPanel, and set the size of the button by setPreferredSize.
Your second attempt should be working, but that does not mean your entire top level container will be filled by the JPanel
that contains your JButton
. When there are no other components in a BorderLayout
container, the center component will expand to fill the entire container.
http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html
If the window is enlarged, the center area gets as much of the available space as possible.
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 JFrame
is also using BorderLayout
. It's possible in your attempt that some upper level container is restricting the size of your JPanel
, and therefore also the JButton
inside.
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(0, 0));
JButton button = new JButton("I'm a button!");
panel.add(button);
frame.getContentPane().add(panel, BorderLayout.CENTER);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With