且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

启动应用程序时设置JFrame的最大大小

更新时间:2022-06-24 14:56:18

我尝试了一下,您说对了,以至于setMaximumSize()无法正常工作.我对限制大小的要求通常由setResizable(false)固定,尽管我看到您对最小和最大大小的特定查询有所不同

I tried it and you're so right that setMaximumSize() doesn't work.. all these years couldn't get to know that!!! Mostly my requirements of limiting size is fixed by setResizable(false), although I see you have specific query of minimum and maximum sizes to be different

尽管如此,但仍为您解决了一个问题:

Worked on a solution for you though:

public class MaxSizeUI
{
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MaxSizeUI().makeUI();
            }
        });
    }

    public void makeUI() {
        final JFrame frame = new JFrame("Sample Fram") {

            @Override
            public void paint(Graphics g) {
                Dimension d = getSize();
                Dimension m = getMaximumSize();
                boolean resize = d.width > m.width || d.height > m.height;
                d.width = Math.min(m.width, d.width);
                d.height = Math.min(m.height, d.height);
                if (resize) {
                    Point p = getLocation();
                    setVisible(false);
                    setSize(d);
                    setLocation(p);
                    setVisible(true);
                }
                super.paint(g);
            }
        };
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 150);
        frame.setMaximumSize(new Dimension(400, 200));
        frame.setMinimumSize(new Dimension(200, 100));
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}