FaceComponent.java.html

  1  import java.awt.Color;
  2  import java.awt.Graphics;
  3  import java.awt.Graphics2D;
  4  import java.awt.Rectangle;
  5  import java.awt.geom.Ellipse2D;
  6  import java.awt.geom.Line2D;
  7  import javax.swing.JComponent;
  8  
  9  /*
 10     A component that draws an alien face
 11  */
 12  public class FaceComponent extends JComponent
 13  {  
 14     public void paintComponent(Graphics g)
 15     {  
 16        // Recover Graphics2D 
 17        Graphics2D g2 = (Graphics2D) g;
 18  
 19        // Draw the head
 20        Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150);
 21        g2.draw(head);
 22  
 23        // Draw the eyes
 24        g2.setColor(Color.GREEN);
 25        Rectangle eye = new Rectangle(25, 70, 15, 15);
 26        g2.fill(eye);
 27        eye.translate(50, 0);
 28        g2.fill(eye);
 29  
 30        // Draw the mouth
 31        Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110);
 32        g2.setColor(Color.RED);
 33        g2.draw(mouth);
 34  
 35        // Draw the greeting
 36        g2.setColor(Color.BLUE);
 37        g2.drawString("Hello, World!", 5, 175);
 38     }
 39  }