有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

FlowLayout对象中的java组件setSize方法

我目前正在制作一个使用FlowLayout类的GUI。现在,这个类的目的是允许组件通过其首选大小的方法进行设置,我相信,在设置组件大小时不应该有优先权。然而,当我对JTextField使用setSize方法时,FlowLayout对象似乎无法识别changesize命令。但是当我使用setColumn方法时,FlowLayout对象确实响应了size命令的更改

为什么会这样


共 (1) 个答案

  1. # 1 楼答案

    FlowLayout object didn't seem to recognize the change size command. But when I used the setColumn method, the FlowLayout object did respond to the change in size command. Why is this?

    从您自己的问题中,我了解到您知道FlowLayout工程遵循组件的首选尺寸。然而,要回答您的问题,为什么JTextFeild.setColumn(int)回答:因为

    一旦调用了setColumn(int),它就会使JTextFeild组件和它上面的所有父级失效(),并将其标记为需要布局的

    public void setColumns(int columns) {
            int oldVal = this.columns;
            if (columns < 0) {
                throw new IllegalArgumentException("columns less than zero.");
            }
            if (columns != oldVal) {
                this.columns = columns;
                invalidate(); // invalidate if column changes
            }
        }
    

    然后,在布局时,FlowLayout调用JTextFeild的getPreferredSize()函数,该函数被重写并实现,以便通过添加列宽返回首选宽度:

    public Dimension getPreferredSize() {
            Dimension size = super.getPreferredSize();
            if (columns != 0) {
                Insets insets = getInsets();
                size.width = columns * getColumnWidth() +
                    insets.left + insets.right;  // changing the width
            }
            return size;
        }
    

    猜猜看!我越来越喜欢源代码了