public Graphics getGraphics() {
if (peer instanceof LightweightPeer) {
// This is for a lightweight component, need to
// translate coordinate spaces and clip relative
// to the parent.
if (parent == null) return null;
Graphics g = parent.getGraphics();
if (g == null) return null;
if (g instanceof ConstrainableGraphics) {
((ConstrainableGraphics) g).constrain(x, y, width, height);
} else {
g.translate(x,y);
g.setClip(0, 0, width, height);
}
g.setFont(getFont());
return g;
} else {
ComponentPeer peer = this.peer;
return (peer != null) ? peer.getGraphics() : null;
}
}
Component没得调用Graphics的构造方法,但是他是如何创建这个对象的昵。
if (peer instanceof LightweightPeer) {
// This is for a lightweight component, need to
// translate coordinate spaces and clip relative
// to the parent.
if (parent == null) return null;
Graphics g = parent.getGraphics();
if (g == null) return null;
if (g instanceof ConstrainableGraphics) {
((ConstrainableGraphics) g).constrain(x, y, width, height);
} else {
g.translate(x,y);
g.setClip(0, 0, width, height);
}
g.setFont(getFont());
return g;
} else {
ComponentPeer peer = this.peer;
return (peer != null) ? peer.getGraphics() : null;
}
}
Component没得调用Graphics的构造方法,但是他是如何创建这个对象的昵。
你可以看到最后一句话peer.getGraphics(),这个东西是在sun包里面,不知道有没源码
你再看Graphics源码,有create无参数的重载方法,是抽象的,留给子类实现
随便找个子类看下
public Graphics create() {
DebugGraphics debugGraphics; debugGraphics = new DebugGraphics();
debugGraphics.graphics = graphics.create();
debugGraphics.debugOptions = debugOptions;
debugGraphics.buffer = buffer; return debugGraphics;
}
它不是graphics的子类的。
getgraphics()自然逃脱不了要调用Graphics的构造函数,这个猜也猜得到,
要不然你去找找看有没sun包的源码吧
Graphics提供的是create封装了构造函数, getgraphics()不是直接调用构造函数也肯定是调用create