How to dynamically control auto-resize components in Java Swing

后端 未结 5 1840
耶瑟儿~
耶瑟儿~ 2020-12-15 22:25

Creating a new GUI in Java (1.8) Swing, I am searching for a way to override resize behavior of all my components.

Let me explain to you with some edited photos:

5条回答
  •  庸人自扰
    2020-12-15 23:17

    You can use a BoxLayout to contain the green and cyan panel. A BoxLayout respects the minimum and maximum sizes of a component. So for the green panel you set then maximum size equal to the preferred size and for the cyan panel you set the minimum size equal to the preferred size:

    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    
    public class SSCCE extends JPanel
    {
        public SSCCE()
        {
            JPanel blue = new JPanel();
            blue.setBackground( Color.BLUE );
            blue.setPreferredSize( new Dimension(500, 100) );
    
            Box box = Box.createHorizontalBox();
    
            JPanel green = new JPanel();
            green.setBackground( Color.GREEN );
            green.setPreferredSize( new Dimension(200, 100) );
            green.setMaximumSize( green.getPreferredSize() );
            box.add( green );
    
            JPanel cyan = new JPanel();
            cyan.setBackground( Color.CYAN );
            cyan.setPreferredSize( new Dimension(300, 100) );
            cyan.setMinimumSize( cyan.getPreferredSize() );
            box.add( cyan );
    
            setLayout( new BorderLayout() );
            add(blue, BorderLayout.NORTH);
            add(box, BorderLayout.CENTER);
        }
    
        private static void createAndShowGUI()
        {
            JFrame frame = new JFrame("SSCCE");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new SSCCE());
            frame.setLocationByPlatform( true );
            frame.pack();
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowGUI();
                }
            });
        }
    }
    

    Of course the proper solution is to override the getMaximumSize() and getMinimumSize() methods respectively of each panel to just return the preferred size of the panel.

提交回复
热议问题