How to restrict size of JButton in GridLayout in Java

If you put the following code in Java with only the lines in blue in your Java Swing program, you will find that whenever the Java dialog is resized, the button grows and looks ugly as it occupies the full row of the GridLayout. Code Segment as below.

     parameterPanel.setLayout(new GridLayout(2,1));
     JButton parameterButton = new JButton("Parameters");
     parameterButton.addActionListener(new ParameterButtonListener());
     parameterPanel.add(parameterButton);

To control the size of the button when resizing, first create an inner JPanel and add the JButton to it (shown in Green text below) and then add the JPanel to the GridLayout. This way the button size is restricted.

     parameterPanel.setLayout(new GridLayout(2,1));
     JButton parameterButton = new JButton("Parameters");
     parameterButton.addActionListener(new ParameterButtonListener());
     JPanel sizePanel = new JPanel();
     sizePanel.add(parameterButton);
     //parameterPanel.add(parameterButton);
     parameterPanel.add(sizePanel);

If you leave the statement in blue without putting in a panel of it’s own, the size of the button will change as the main window is resized. To restrict, change the red color statements to the green ones.

Leave a Reply

  

  

  

Blue Captcha Image
Refresh

*

October 2019
M T W T F S S
« Sep    
 123456
78910111213
14151617181920
21222324252627
28293031