简体   繁体   English

如何设置 JFrame 的最小尺寸,以阻止用户将其调整为更小?

[英]How can I set a minimum size of a JFrame, to stop the user to resize it to smaller?

I have a JFrame which cannot be smaller than a specific size, or the elements cannot lay out properly.我有一个不能小于特定大小的JFrame ,或者元素无法正确布局。

I tried to setMinimumSize() and overwrite the getMinimumSize() method of this frame, but I can still resize the frame to smaller.我尝试setMinimumSize()并覆盖此框架的getMinimumSize()方法,但我仍然可以将框架调整为更小。

So, must I listen to the change of bounds in my componentListener when componentResized() , and if it's smaller, set it back to normal size with setBounds() ?那么,我是否必须在componentResized()时监听我的componentListener中边界的变化,如果它更小,请使用setBounds()将其设置回正常大小?

With the lack of compilable code, it is hard to tell what is going wrong there / in your code.由于缺乏可编译的代码,很难判断代码中/中出了什么问题。 Possibly the call the setMinimumSize(..) is occurring at the wrong time and/or with the wrong values.可能调用setMinimumSize(..)发生在错误的时间和/或错误的值。

Here, this code will not allow the frame to go smaller than it first appears, but will allow the user to drag it larger.在这里,此代码将不允许框架变得比最初出现的更小,但允许用户将其拖动得更大。 Check the comments for tips.查看评论以获取提示。

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class MinimumSizeFrame {

    private JComponent ui = null;

    MinimumSizeFrame() {
        ui = new JPanel(new BorderLayout(4,4));

        JLabel label = new JLabel("Text in big label");
        label.setBorder(new EmptyBorder(40, 100, 40, 100));
        ui.add(label);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            MinimumSizeFrame o = new MinimumSizeFrame();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            // have the JVM calculate the ideal size of this GUI
            f.pack(); 
            // now use THAT as minimum size!
            f.setMinimumSize(f.getSize()); 

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

您可以尝试在框架初始化中使用以下属性以避免调整大小

setResizable(false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM