如何设置 JFrame 的最小尺寸,以阻止用户将其调整为更小? [英] How can I set a minimum size of a JFrame, to stop the user to resize it to smaller?

查看:20
本文介绍了如何设置 JFrame 的最小尺寸,以阻止用户将其调整为更小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JFrame,它不能小于特定大小,或者元素无法正确布局.

I have a JFrame which cannot be smaller than a specific size, or the elements cannot lay out properly.

我尝试了 setMinimumSize() 并覆盖此框架的 getMinimumSize() 方法,但我仍然可以将框架调整为更小.

I tried to setMinimumSize() and overwrite the getMinimumSize() method of this frame, but I can still resize the frame to smaller.

所以,我必须在 componentResized() 时监听我的 componentListener 中边界的变化,如果它更小,用 将其设置回正常大小setBounds()?

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()?

推荐答案

由于缺乏可编译的代码,很难判断代码中/那里出了什么问题.可能调用 setMinimumSize(..) 发生在错误的时间和/或错误的值.

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.

在这里,这段代码不允许框架比它第一次出现时更小,但允许用户将它拖得更大.查看评论以获取提示.

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);
    }
}

这篇关于如何设置 JFrame 的最小尺寸,以阻止用户将其调整为更小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆