Why setPreferredSize does not change the size of the button?

17,691

Solution 1

Layout managers are free to ignore the preferred size. Specifically, GridLayout will always make each cell in the grid exactly the same size (it's a pretty useless layout manager for that reason).

You'll have to use a different layout manager, such as nested BoxLayout or a GroupLayout.

Solution 2

GridLayout is quite inflexible in that each and every cell is the same size, typically honoring the largest height and width settings of any object added to the grid.

If the rows and/or columns need to have varying sizes you should use GridBagLayout.

Share:
17,691
Roman
Author by

Roman

Updated on June 04, 2022

Comments

  • Roman
    Roman about 2 years

    Here is the code:

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    
    public class TestGrid {
    
        public static void main(String[] args) {
            JFrame frame = new JFrame("Colored Trails");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JPanel mainPanel = new JPanel();
            mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    
            JPanel panel = new JPanel();
            panel.setLayout(new GridLayout(4, 9));
            panel.setMaximumSize(new Dimension(9*30-20,4*30));
    
            JButton btn;
            for (int i=1; i<=4; i++) {
                for (int j=1; j<=4; j++) {
                    btn = new JButton();
                    btn.setPreferredSize(new Dimension(30, 30));
                    panel.add(btn);
                }
    
                btn = new JButton();
                btn.setPreferredSize(new Dimension(30, 10));
                panel.add(btn);
    
                for (int j=1; j<=4; j++) {
                    btn = new JButton();
                    btn.setPreferredSize(new Dimension(30, 30));
                    panel.add(btn);
                }
    
            }
            mainPanel.add(panel);
            frame.add(mainPanel);
    
            frame.setSize(450,950);
            frame.setVisible(true);
        }
    }
    

    I suppose to have a table of buttons with 4 rows and 9 columns. And the middle column should be narrower that other columns. I tried Dimension(30, 10) and Dimension(30, 10) both have no effect on the width of the middle column. Why?

  • Michael
    Michael about 12 years
    In this case setting Dimension won't help. GridLayout is being used which doesn't fully honor setPreferredSize. GridLayout sets all heights and widths the same based on the largest width and height. Also, note that the largest height and width does not have to come from the same component.