问题
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