我目前正在制作一个使用 FlowLayout 类的 GUI。现在,此类旨在允许通过其首选大小的方法来设置组件,并且我相信,不应该优先设置组件大小。但是,当我对 JTextField 使用 setSize 方法时,FlowLayout 对象似乎无法识别更改大小命令。但是当我使用 setColumn 方法时,FlowLayout 对象确实响应了大小命令的更改。
这是为什么?
最佳答案
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;
}
你猜怎么着!我正在成为源代码的粉丝。
关于java - FlowLayout对象中的组件setSize方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19472146/