System.out.print(thingy)
只是打印方法thingy.toString()
toString()
forJPanel
来自java.awt.Component
类:
public String toString() {
return getClass().getName() + "[" + paramString() + "]";
}
调用protected String paramString()
它会导致我们回到JPanel
这个方法被覆盖的地方:
/**
* Returns a string representation of this JPanel. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this JPanel.
*/
protected String paramString() {
return super.paramString();
}
这使我们JCompomnent
看到了它的第一级父类JPanel
(但它仍然没有显式声明,因此每个 JComponent 都会调用toString()
这个 from ,包括 JPanel)。
所以,它被调用:java.awt.Component
paramString()
protected String paramString() {
String preferredSizeString = (isPreferredSizeSet() ?
getPreferredSize().toString() : "");
String minimumSizeString = (isMinimumSizeSet() ?
getMinimumSize().toString() : "");
String maximumSizeString = (isMaximumSizeSet() ?
getMaximumSize().toString() : "");
String borderString = (border != null ?
border.toString() : "");
return super.paramString() +
",alignmentX=" + alignmentX +
",alignmentY=" + alignmentY +
",border=" + borderString +
",flags=" + flags + // should beef this up a bit
",maximumSize=" + maximumSizeString +
",minimumSize=" + minimumSizeString +
",preferredSize=" + preferredSizeString;
}
......再一次 - super.paramString()
- 从java.awt.Container
protected String paramString() {
String str = super.paramString();
LayoutManager layoutMgr = this.layoutMgr;
if (layoutMgr != null) {
str += ",layout=" + layoutMgr.getClass().getName();
}
return str;
}
......再一次- super.paramString()
- 这最终让我们回到java.awt.Component
protected String paramString() {
String thisName = getName();
String str = (thisName != null? thisName : "") + "," + x + "," + y + "," + width + "x" + height;
if (!isValid()) {
str += ",invalid";
}
if (!visible) {
str += ",hidden";
}
if (!enabled) {
str += ",disabled";
}
return str;
}
invalid
这是打印在描述 JPanel 的字符串中的根本原因
/**
* Determines whether this component is valid. A component is valid
* when it is correctly sized and positioned within its parent
* container and all its children are also valid.
* In order to account for peers' size requirements, components are invalidated
* before they are first shown on the screen. By the time the parent container
* is fully realized, all its components will be valid.
* @return <code>true</code> if the component is valid, <code>false</code>
* otherwise
* @see #validate
* @see #invalidate
* @since JDK1.0
*/
public boolean isValid() {
return (peer != null) && valid;
}
valid
@Reimeus 很好地解释了如何实现状态