FlowLayout对象中的组件setSize方法

FlowLayout对象中的组件setSize方法

本文介绍了FlowLayout对象中的组件setSize方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在制作一个使用FlowLayout类的GUI.现在,此类旨在允许通过组件的首选大小的方法来设置组件,我认为,在设置组件大小方面不应该具有优先权.但是,当我对JTextField使用setSize方法时,FlowLayout对象似乎无法识别更改大小命令.但是当我使用setColumn方法时,FlowLayout对象确实响应了大小命令的更改.

I'm currently making a GUI that makes use of the FlowLayout class. Now, this class is meant to allow components be set by their prefer sized methods and I believe, isn't supposed to have priority in setting the component size. However, when I used a setSize method for a JTextField, the 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.

这是为什么?

推荐答案

提出您自己的问题,我了解您知道 FlowLayout 可以遵循组件的首选大小.但是要回答您的问题,为什么 JTextFeild.setColumn(int)真正响应:因为

Form your own question i understand that you know FlowLayout works obeying component's preferred size. However to answer your question why really JTextFeild.setColumn(int) responds: Because,

一旦调用 setColumn(int),它将使 JTextFeild 组件及其上面的所有父级都无效(),将其标记为布置.

As soon as setColumn(int) is called, it invalidate() the JTextFeild component and and all parents above it to be marked as needing to be laid out.

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()函数,该函数将被覆盖并实现,以便通过添加列宽来返回首选宽度:

Then while laying out, FlowLayout calls the getPreferredSize() function of JTextFeild, which is overridden and implemented such that it returns the preferred width by adding the column width:

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

猜猜是什么!我正在成为源代码的粉丝.

Guess what! I am becoming fan of source code.

这篇关于FlowLayout对象中的组件setSize方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 22:28