Component setSize method in FlowLayout object

混江龙づ霸主 提交于 2021-02-11 17:24:17

问题


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.

Why is this?


回答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?

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,

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

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.



来源:https://stackoverflow.com/questions/19472146/component-setsize-method-in-flowlayout-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!