FlowLayout对象中的组件setSize方法

时间:2013-10-19 23:10:45

标签: java swing components flowlayout preferredsize

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

为什么会这样?

1 个答案:

答案 0 :(得分:1)

  

FlowLayout对象似乎没有识别change size命令。   但是当我使用setColumn方法时,FlowLayout对象就是这样做的   响应size命令的变化。 为什么会这样?

形成您自己的问题我知道您知道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;
    }
猜猜是什么!我正在成为源代码的粉丝。