Academic Java    Java Tutorial  >  Graphics  >  graphics context (2D)

graphics context Example

Java graphics context EXAMPLE output This applet uses 2D graphics to draw rectangles.

First the Graphics parameter passed to paint() is cast to Graphics2D.

This graphics context gives a wider range of rendering capabilities than Graphics.

The setPaint() method is used with g2. It is more general than setColor() and can also handle gradient paint.
//Graphics Context 2D Graphics Example
import java.awt.*;
import javax.swing.*;

class GraphicsContextExample3 extends JApplet {

   @Override public void paint(Graphics g) {
      super.paint(g);

      Graphics2D g2 = (Graphics2D)g;

      g2.setPaint(Color.magenta);
      g2.drawRect(50, 50, 50, 50);

      g2.setStroke(new BasicStroke(10));
      g2.drawRect(150, 150, 50, 50);

      g2.setPaint(Color.cyan);
      g2.fillRect(155, 155, 40, 40);

   }
}


* graphics context Examples