Here's my code:
这是我的代码:
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.drawString("This is my string", 200, 200);
}
This works correctly; the text comes out as anti-aliased. However, why does it work? The text is drawn by the g object, however as far as I can see, the anti-aliasing was turned on for the g2 object. How does the g object get it?
这工作正常;文本出现反锯齿。但是,它为什么有用呢?文本由g对象绘制,但是据我所知,为g2对象打开了抗锯齿。 g对象如何获得它?
2 个解决方案
#1
Graphics2D g2 = (Graphics2D) g;
Both g and g2 are references to the same object (g). g refers to the object as Graphics2D whereas g2 refers to the object as Graphics2D.
g和g2都是对同一对象(g)的引用。 g将对象称为Graphics2D,而g2将对象称为Graphics2D。
#2
g
and g2
are both references to the same object. In runtime, the type of the reference doesn't really matter - you have that object run a method.
g和g2都是对同一对象的引用。在运行时,引用的类型并不重要 - 您有该对象运行方法。
#1
Graphics2D g2 = (Graphics2D) g;
Both g and g2 are references to the same object (g). g refers to the object as Graphics2D whereas g2 refers to the object as Graphics2D.
g和g2都是对同一对象(g)的引用。 g将对象称为Graphics2D,而g2将对象称为Graphics2D。
#2
g
and g2
are both references to the same object. In runtime, the type of the reference doesn't really matter - you have that object run a method.
g和g2都是对同一对象的引用。在运行时,引用的类型并不重要 - 您有该对象运行方法。