Graphics

Graphics
Shapes

 
 
 

Colors
public void paint( Graphics g ){
    // Colors
     g.setColor(Color.green);
    // custom colors
     Color myOrange = new Color(230,92,0); // the amount of red, green, blue in the color. Each component has a value from 0-255.
  

Shapes – Examples (Rect, Oval, Arc, Line)
   //shapes
     g.drawRect(50,20,100,200); // g.fillRect(600, 400, 50, 50); // draw a rectangle
     g.drawOval(50,20,100,200); // g.fillOval(100,20,150,200); // draw a filled-in oval
   //arcs - start at x axis counterclockwise degrees
     g.drawArc(270,20,100,200,0,270); // draw an arc that starts at 0 degrees and has an arclength of 270 degrees
     g.drawArc(50,250,150,150,90,180); // from 90 degrees counterclockwise of x axis to 270 (90+180)
     g.drawArc(210,250,150,150,45,90); // from 45 degrees to 135 (45+90)
     g.fillArc(210,280,150,150,45,90); // ditto, but filled in
   // line
     g.drawLine(50,150,100,180); // draw diagonal line
     g.drawLine(x,y,x,y); // drawing a line from a point to itself makes a 1px-by-1px dot
  

Shapes – Example (3d box)
// Draw a basic 3D box
   Rectangle face = new Rectangle(20,30,100,40);
        face.draw();
        Line line1 = new Line(20,30,50,10);
        line1.draw();
        Line line2 = new Line(120,70,150,50);
        line2.draw();
        Line line3 = new Line(120,30,150,10);
        line3.draw();
        Line line4 = new Line(50,10,150,10);
        line4.draw();
        Line line5 = new Line(150,10,150,50);
        line5.draw();
 
Fonts
   g.setColor(Color.white);
   g.setFont(new Font("Calibri", Font.BOLD+Font.ITALIC, 60)); // 60-pt italic bold
   g.drawString("Leander Lions", 300, 350);

   g.setColor(Color.blue);
   g.setFont(Font.decode("Calibri-BOLDITALIC-60")); // a different way to specify the same font
   g.drawString("Leander Lions", 290, 360);

   g.setColor(Color.black);
   g.setFont(new Font(null)); // restore default font
  

Graphics - Example Graphics Code

//Example code
import java.awt.*; // Need to learn what this does
import javax.swing.JFrame; // Need to learn what this does

public class className extends Canvas{
public void paint( Graphics g ){
  g.setColor(Color.green);
  g.drawRect(50,20,100,200); // draw a rectangle; (starting x, starting y, x width from left, y width from top)

  g.setColor(Color.black);
  g.drawString("Graphics are pretty neat.", 500, 100); // (draw string starting at, starting x, starting y)
  int x = getWidth() / 2; //get width of window and divide it by 2
  int y = getHeight() / 2; //get width of window and divide it by 2
  g.drawString("The first letter of this string is at (" + x + "," + y + ")", x, y);
}

public static void main( String[] args ){
  JFrame win = new JFrame("GraphicsDemo1"); //frame title
  win.setSize(800,600); //frame size
  win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  className canvas = new className();
  win.add( canvas );
  win.setVisible(true);
}