ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-如何使用GridBagLayout设置最小尺寸?

2019-10-30 09:00:19  阅读:243  来源: 互联网

标签:gridbaglayout layout swing java minimum-size


我有一个使用GridBagLayout的简单GUI,顶部有一个按钮面板,而一个自定义可调整大小的组件占用了其余的空间,如下图所示:

定制组件(红色组件)的首选大小为(400,300),最小大小为(40,30),并且很高兴将其调整为更大的大小.
但是,我希望我的框架遵守按钮面板的最小尺寸,并且不允许调整框架的大小,以使任何按钮都不能完全显示在屏幕上.这不是当前的行为,因为我可以将其调整为远远超出这些边界的大小,如下所示:

我当前的代码如下:

import javax.swing.*;
import java.awt.*;

public class Example {
    public static void main(String[] args) {
        // Setup JFrame and GridBagLayout.
        JFrame frame = new JFrame("Example");
        Container contentPane = frame.getContentPane();
        GridBagLayout layout = new GridBagLayout();
        contentPane.setLayout(layout);
        layout.rowWeights = new double[] {0.0, 1.0};
        layout.columnWeights = new double[] {1.0};
        GridBagConstraints cons = new GridBagConstraints();

        // Add button panel with a BoxLayout.
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
        panel.add(new JButton("Button 1"));
        panel.add(new JButton("Button 2"));
        panel.add(new JButton("Button 3"));
        cons.anchor = GridBagConstraints.NORTHWEST;
        cons.gridx = 0;
        cons.gridy = 0;
        layout.setConstraints(panel, cons);
        contentPane.add(panel);

        // Add custom component, resizable.
        JComponent custom = new JComponent() {
            public Dimension getPreferredSize() {
                return new Dimension(400, 300);
            }

            public Dimension getMinimumSize() {
                return new Dimension(40, 30);
            }

            public void paintComponent(Graphics g) {
                g.setColor(Color.RED);
                g.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        cons.gridx = 0;
        cons.gridy = 1;
        cons.fill = GridBagConstraints.BOTH;
        layout.setConstraints(custom, cons);
        contentPane.add(custom);

        // Pack and show frame.
        frame.pack();
        frame.setVisible(true);
    }
}

我已经在Mac OS X 10.8(Java 6)和Ubuntu 3.2.8(Java 6)上进行了测试,并观察到相同的结果.

如何防止调整框架大小以覆盖任何按钮?更一般而言,如何使GridBagLayout真正遵守组件的最小尺寸?当我打印出框架的最小尺寸时,我得到(291,81),这正是我想要的,但是当我调整框架的尺寸时,它超出了这个范围.

注意:我看过this related question,但它似乎无法回答我的问题.

解决方法:

我不确定为什么,但是如果我使用…

frame.setMinimumSize(frame.getMinimumSize());

创建UI后(显然),它可以工作.

我“认为”这与((WindowPeer)peer).updateMinimumSize();有关.在Window的setMinimumSize size方法中…

标签:gridbaglayout,layout,swing,java,minimum-size
来源: https://codeday.me/bug/20191030/1966754.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有