如何使GridBagLayout特定大小? [英] How to make GridBagLayout specific size?

查看:254
本文介绍了如何使GridBagLayout特定大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻,我已经使用GridBayLayout获得了一个9x9的文本字段网格.由于网格使每个文本字段的长度稍长于其高度(即使我为文本字段设置了特定的高度),所以网格是矩形而不是正方形.

At the moment I've got a 9x9 grid of text fields using a GridBayLayout. Because the grid makes each text field slighter longer than it is tall (even when I set a specific height for the text field), the grid is a rectangle, rather than a square.

如何使整个网格具有特定的大小,或者使网格内的每个文本字段具有特定的大小?

How can I either make the entire grid a specific size, or each text field inside the grid a specific size?

我需要9 x 9的文本字段网格为正方形,而不是矩形.

I need the 9 x 9 grid of text fields to be square, rather than rectangular.

推荐答案

问题在于尺寸调整提示,方法[get/set][Minimum/Maximum/Preferred]Size告诉布局管理器组件想要的尺寸,布局管理器有时忽略该大小,有时不这样做没错GridBagLayout尊重您,您的JTextFields告诉他他们想成为矩形. JTextFields如何确定他们想要的大小是很困难的,所以让我们省略一下.

The problem is with sizing hints, methods [get/set][Minimum/Maximum/Preferred]Size are telling the layout manager what size the component wants to be and layout managers sometimes ignore that and sometimes they don't. GridBagLayout respects that and your JTextFields are tellimg him that they want to be rectangular. How JTextFields figure out what size they want to be is all kinds of difficult so let's leave that out.

如果要确保所有JTextFields的大小均相同,则应覆盖这些方法.子类JTextField并进行如下操作:

If you want to make sure that all your JTextFields are of the same size, you should override these methods. Subclass JTextField and make something like this:

final class SquareJTextField extends JTextField {
    private static Dimension maxDimension = new Dimension(0, 0);

    @Override
    public Dimension getPreferredSize() {
        Dimension d = super.getPreferredSize();
        // take the larger value
        int max = d.width > d.height ? d.width : d.height;
        // compare it against our static dimension
        // height je rovnaky ako width
        if (max > maxDimension.width)
            maxDimension = new Dimension(max, max);
        // return copy so no one can change the private one
        return new Dimension(maxDimension);
    }

    @Override
    public Dimension getMinimumSize() {
        Dimension d = super.getPreferredSize();
        int max = d.width > d.height ? d.width : d.height;
        if (max > maxDimension.width)
            maxDimension = new Dimension(max, max);
        return new Dimension(maxDimension);
    }

    @Override
    public Dimension getMaximumSize() {
        Dimension d = super.getPreferredSize();
        int max = d.width > d.height ? d.width : d.height;
        if (max > maxDimension.width)
            maxDimension = new Dimension(max, max);
        return new Dimension(maxDimension);
    }
}

此类的所有对象都应具有相同的尺寸,并且应为正方形.

All objects of this class should be the same dimension and should be square.

SquareJTextField

这篇关于如何使GridBagLayout特定大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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