Search code examples
javaswinglayout-managergridbaglayout

How to make GridBagLayout specific size?


At the moment I've got a 9x9 grid of text fields using a GridBayLayout. Because the grid makes each text field slighter longer than it is tall (even when I set a specific height for the text field), the grid is a rectangle, rather than a square.

How can I either make the entire grid a specific size, or each text field inside the grid a specific size?

EDIT: I need the 9 x 9 grid of text fields to be square, rather than rectangular.


Solution

  • The problem is with sizing hints, methods [get/set][Minimum/Maximum/Preferred]Size are telling the layout manager what size the component wants to be and layout managers sometimes ignore that and sometimes they don't. GridBagLayout respects that and your JTextFields are tellimg him that they want to be rectangular. How JTextFields figure out what size they want to be is all kinds of difficult so let's leave that out.

    If you want to make sure that all your JTextFields are of the same size, you should override these methods. Subclass JTextField and make something like this:

    final class SquareJTextField extends JTextField {
        private static Dimension maxDimension = new Dimension(0, 0);
    
        @Override
        public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            // take the larger value
            int max = d.width > d.height ? d.width : d.height;
            // compare it against our static dimension
            // height je rovnaky ako width
            if (max > maxDimension.width)
                maxDimension = new Dimension(max, max);
            // return copy so no one can change the private one
            return new Dimension(maxDimension);
        }
    
        @Override
        public Dimension getMinimumSize() {
            Dimension d = super.getPreferredSize();
            int max = d.width > d.height ? d.width : d.height;
            if (max > maxDimension.width)
                maxDimension = new Dimension(max, max);
            return new Dimension(maxDimension);
        }
    
        @Override
        public Dimension getMaximumSize() {
            Dimension d = super.getPreferredSize();
            int max = d.width > d.height ? d.width : d.height;
            if (max > maxDimension.width)
                maxDimension = new Dimension(max, max);
            return new Dimension(maxDimension);
        }
    }
    

    All objects of this class should be the same dimension and should be square.

    Replace JtextFields in your grid with SquareJTextField