One of the most popular things Java is used for is to make online games. While making 3d games is near impossible, two dimensional games are very do-able.
Although designing an entire game is beyond the scope of this tutorial, I will introduce to you the basic use of the graphics library.
We are going to implement this into a applet to lets start with the basic framework.
Java Code:
package tutorials;
import javax.swing.JApplet;
public class GraphicsTut
extends JApplet {
public void init() {
System.
out.
println("The applet has initialized");
}
}
Next we are going to import the graphics class located in the java.awt package.
Java Code:
package tutorials;
import java.awt.Graphics;
import javax.swing.JApplet;
public class GraphicsTut
extends JApplet {
public void init() {
System.
out.
println("The applet has initialized");
}
}
Then we are going to override the paint method.
Java Code:
package tutorials;
import java.awt.Graphics;
import javax.swing.JApplet;
public class GraphicsTut
extends JApplet {
public void init() {
System.
out.
println("The applet has initialized");
}
}
}
Once we are at this point, we can call many methods on the Graphics object "g." I'm going to create a simple square. To do that we are going to use the
drawRect() method which requires four parameters. The x location of the upper left corner, the y location of the upper left corner, the width, and the
height. We end up with a class that looks like this:
Java Code:
package tutorials;
import java.awt.Graphics;
import javax.swing.JApplet;
public class GraphicsTut
extends JApplet {
public void init() {
System.
out.
println("The applet has initialized");
}
g.drawRect(10, 10, 100, 100);
}
}