public class FaceComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150);
Rectangle eye = new Rectangle(25, 70, 15, 15);
Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110);
g2.setColor(Color.GREEN)
.fill(eye)
.eye.translate(50, 0);
.fill(eye)
.setColor(Color.RED)
.draw(mouth)
.setColor(Color.BLUE)
.drawString("Hello, World!", 5, 175);
}
}
是否有原因在对象g2上链接方法导致错误“无法在原始类型void上调用(方法),我可能会忽略该错误?
最佳答案
方法setColor
,fill
等具有无效的返回类型,因此不能像这样链接,而需要分别调用
g2.setColor(Color.GREEN);
g2.fill(eye);
...