Java:Tutorials:Graphics

From GPWiki
Jump to: navigation, search

Graphics and Techniques

I find that the easiest way to implement graphics in a Java application is with the JFrame. I start by creating a shell which opens a window that we can draw onto. Start by importing java.awt.* java.awt.event.* and javax.swing.*.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

Then make sure your class extends JFrame. Within the constructor call setVisible(true); and setSize(Xwidth, Ywidth);

public class simplegraphics extends JFrame
{
  public simplegraphics()
  {
    setVisible(true);
    setSize(300, 200);
  }

Next you need a paint method.

  public void paint(Graphics g)
  {
    //some code where painting occurs
  }

Then in your main method declare a new simplegraphics, and call the repaint function.

  public static void main(String args[])
  {
    simplegraphics SG = new simplegraphics();
    SG.repaint();
  }
}

Painting

public void paint(Graphics g)
{
  g.translate(x, y); //Moves the origin 0,0 to this point.
  g.setColor(Color.red);//Color can be replaced by one of multiple 
                     //predefined color or created manualy.
                     //Such as  Color.blue Color.green or 
                     //new Color(Red_Amount, Green_Amount, Blue_Amount)
  g.drawLine(x, y, width, height); //there are more commands than whats shown here.
  g.drawRect(x, y, width, height);
  g.fillRect(x, y, width, height);
  g.drawOval(x, y, xRadius, yRadius);
  g.fillOval(x, y, xRadius, yRadius);
}

Technique/Animation

By making these changes or copying and pasting; this program is a demonstration on animating a ball bounce back and forth.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class simplegraphics extends JFrame
{
  int x = 150, y = 100, xdir = 1, ydir = 2;
  public simplegraphics()
  {
    boolean initial=true;
    setVisible(true);
    setSize(300, 200);
  }
  public void paint(Graphics g)
  {
  	g.translate(0, 25);           //move origin down to compromise for the title bar
 
  	g.setColor(Color.white);                   //background color
  	g.fillRect(0, 0, getWidth(), getHeight()); //background
 
  	g.setColor(Color.white);      //clears the old ball
  	g.fillOval(x, y, 20, 20);        
  	move();                       //updates the balls position
        g.setColor(Color.red);        //draws a new ball
  	g.fillOval(x, y, 20, 20);	
 
  }
  public void move()
  {
  	if(x < 0 || x > getWidth() - 20)
  		xdir *= -1;
  	if(y < 0 || y > getHeight() - 45)
  		ydir *= -1;
  	x += xdir;
  	y += ydir;
  }
  public static void main(String args[])
  {
    simplegraphics SG = new simplegraphics(); 
    int step = 0;
    while(true)
    {
    	if(step % 500000 == 0) //the number 500000 doesn't matter but a smaller number will make the
                               //animation, not the ball, speed up.
    	{
    		SG.repaint();
    	}
    	step++;
    }
  }
}

--techno 00:02, 24 May 2005 (EDT)