Jump to content
xisto Community
Sign in to follow this  
beeseven

An Introduction To Java And Graphics

Recommended Posts

Table of Contents

I. Introduction

II. Before You Begin

III. Necessities in a Java Program

IV. Creating a Canvas

V. Shapes

????[/TAB]A. Line

????B. Rectangle

????C. Oval

????D. Polygon

VI. Other Things

????A. Changing the Color

????B. Strings

????????1. Changing the Font

????????2. Drawing a String

[TAB]C. Images

VII. Conclusion

 

I. Introduction

Welcome to my second tutorial here at Xisto. I'm going on vacation for a week so I thought I'd leave you all with some of the things that I picked up in the class I took ealier this summer. If anyone wants to see some things that I've done, too bad. If you want to see one thing that I've done, that's okay, because only one thing I've done is anywhere near showable. My final project was Mario, and you can download it at tjhsst.edu/~tsmilack/java/mario. The filenames work like dates (MMDDYY), so 080505 is newer than 080405. I also plan on working on this more, so watch for updates. Anyway, on to the tutorial.

 

II. Before You Begin

Before you start, you'll need the Java Software Developer's Kit and a compiler. The SDK you can get from the Java website (java.sun.com). They also have an installation guide located at java.sun.com/developer/onlineTraining/new2java/programming/learn/. As for a compiler, it depends on your computer. If your computer is just okay, or it doesn't really like Java, use pcGRASP (http://www.eng.auburn.edu/grasp/archive.html). If your computer is pretty good jGRASP (spider.eng.auburn.edu/user-cgi/grasp/grasp.pl?;dl=download_jgrasp.html) might be better, but it all comes down to preference.

 

III. Necessities in a Java Program

Okay, now that you've installed the SDK and your compiler, it's time to learn the basic things that you must have in a Java program. In this tutorial I'll be working with JFrames as opposed to applets, so if you're familiar with Java and JFrames you might be able to skip this part (and maybe the next). Anyway, on to the code.

 

First of all, you'll need to have a .java file. In this file you will put all your code. The thing that you put your code in inside the .java file is called a class. The class should have the same name as the .java file (eg Hello.java's class would be Hello). To define a class, generally you say "public class ClassName". You don't always say public, but for now we will. By convention the first letter of the class name is capitalized and the first letters of any subsequent words in the name are also capital. Everything in a class is enclosed in curly braces ( { and } ). We'll call our file "Grapics1.java," so right now we have:

 

Graphics1.java:

public class Graphics1{}

Since we're going to be putting this in a JFrame it has to be a subclass of a JPanel, so we then change it to this:

 

Graphics1.java:

public class Graphics1 extends JPanel{}

However, the compiler won't know what a JPanel is, so we have to "import" some things. This just makes them available to use (it is the same as "include" in other languages). One of the best things about Java is that there are so many things to use that people have already made.

 

Graphics1.java:

import javax.swing.*; //JFrame, JPanelimport java.awt.*; //Graphicspublic class Graphics1 extends JPanel{}

Since this isn't going to be an applet (we would have said "extends JApplet" in that case), we need to have a method called main (methods are called functions in some other languages). Main always must have the same header, and method bodies must also be inside curly braces.

 

Graphics1.java:

import javax.swing.*; //JFrame, JPanelimport java.awt.*; //Graphicspublic class Graphics1 extends JPanel{     public static void main(String[] args)     {          }}

IV. Creating a Canvas

To create a JFrame, you must create a new JFrame object. This will automatically make a window pop up and be all windowy. There are several things to do to create this, and most of them shouldn't be changed. Here is the code to create a new JFrame and add our Graphics1 panel to it:

 

Graphics1.java:

import javax.swing.*; //JFrame, JPanelimport java.awt.*; //Graphicspublic class Graphics1 extends JPanel{     public static void main(String[] args)     {          JFrame f = new JFrame("This is the title that appears in the upper left");  //Single line comments are made with two slashes          f.setSize(500,500); //Width in pixels, height in pixels          f.setLocation(100,100); //x, y from 0,0 (0,0 is top left corner of screen)          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This should not be changed or your program will not terminate properly. JFrame.EXIT_ON_CLOSE is an integer variable, so if you want to type less, it's actually 3          f.setContentPane(new Graphics1()); //adds our panel          f.setVisible(true); //makes the window visible     }}

Now this won't really do anything because all we've done is created a panel. Therefore, we have to define the method paintComponent in order to make out picture pretty. Now Graphics1 will look like this:

 

Graphics1.java:

import javax.swing.*; //JFrame, JPanelimport java.awt.*; //Graphicspublic class Graphics1 extends JPanel{     public static void main(String[] args)     {          JFrame f = new JFrame("This is the title that appears in the upper left");  //Single line comments are made with two slashes          f.setSize(500,500); //Width in pixels, height in pixels          f.setLocation(100,100); //x, y from 0,0 (0,0 is top left corner of screen)          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This should not be changed or your program will not terminate properly. JFrame.EXIT_ON_CLOSE is an integer variable, so if you want to type less, it's actually 3          f.setContentPane(new Graphics1()); //adds our panel          f.setVisible(true); //makes the window visible     }     public void paintComponent(Graphics g)     {          super.paintComponent(g); //This pretty much just makes the background grey     }}

Now we have our canvas. All the painting will go inside the method paintComponent.

 

V. Shapes

Shapes need to have a pair of coordinates specified. The coordinate system is a little weird, in that (0,0) is at the top left of the window. X increases to the right (as usual), but Y increases as you go down. The reason for this is that most people resize things from the bottom right corner, so it makes sense to have the origin at a fixed point. On to the shapes.

 

A. Line

Lines are very simple. They take four arguments, and they are x1, y1, x2, and y2. You call the method by saying (graphics object).drawLine(...). In this case our graphics object is called g, so we add this to paintComponent:

public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);}

This draws a line from (0,0) to (100,100).

 

B. Rectangle

Rectangles are similar to lines, but instead of x2 and y2, the third and fourth arguments and width and height:

public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);}

Now we have our original line, plus a square that encompasses the line. With rectangles and other shapes besides lines, you can also do a fill. You just change "draw" to "fill":
public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.fillRect(0,0,100,100);}

This makes a filled square. I won't mention fills again because it's all the same. The default color for all lines and shapes and things is black, but I'll say how to change it later.

 

C. Oval

Ovals are very much like rectangles, but, well, ovals. The arguments are the same: x, y, w, h. The top left corner of the oval is the same as the top left corner of the rectangle that it is circumscribed in:

public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);}

This makes a circle inside the rectangle we drew previously. There is no specific "drawCircle" method, but you can just make the width and height the same. To make a circle centered at x,y with radius r, say this:
g.drawOval(x + r, y + r, 2 * r, 2 * r);

D. Polygon

Polygons are a bit harder. They require arrays of points but can make pretty much any shape. The arguments are defined as "int[] xPoints, int[] yPoints, int nPoints." That means "an array of integers xPoints, an array of integers yPoints, and the number of points nPoints." Here's how it works:

public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);}

This new piece of code draws a triangle with points at (0,0), (100,0), and (0,100).

 

VI. Other Things

You can do more than just black shapes. Here I'll show you a few other things.

 

A. Changing the Color

Changing the color is relatively simple. The method takes one argument, but you must pass it a color object:

g.setColor(new Color(255,0,0));g.setColor(Color.red);

Both of these will set the color to red, but a Color.(color) doesn't exist for every color, so knowledge of the RGB system is helpful (if you don't know it there's probably something on Google, just search "color chooser"). Now we'll set the draw color to blue before our next section:
public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);     g.setColor(new Color(0,0,255));}
B. Strings

You should all know what strings are. They're just strings of characters, like "hello" or "kjekt43543 34hkdsg-43 gdf4(*%#." Sometimes it's useful to put a string on a image, and that's what this section's about.

 

1. Changing the Font

Like a color, setFont requires one variable but you must have a new object for it. To make a font object, you must give the name, style, and size. Universally supported names are "Serif," "SansSerif," and "Monospaced," but you can also use names like "Arial" and "Tahoma." Style is bold (Font.BOLD), italic (Font.ITALIC), or bold italic (Font.BOLD | Font.ITALIC). Size is a numeric representation of the size. Here is an example:

public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);     g.setColor(new Color(0,0,255));     g.setFont(new Font("Serif", Font.BOLD, 14));}

This makes a 14pt bold serif font.

 

2. Drawing a String

The method drawString takes three arguments: the string to be drawn, the x coordinate and the y coordinate. For strings, the x and y values are at the bottom left of the string as opposed to top left. Here is how to use drawString:

public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);     g.setColor(new Color(0,0,255));     g.setFont(new Font("Serif", Font.BOLD, 14));     g.drawString("Hello World!",100,100);}

This draws the string "Hello World!" just to the right of our square.

 

C. Images

Images are a bit complicated. You have to import the ImageIcon class (which is in javax.swing.* so we're okay here). You create an image by making a new ImageIcon and giving it a string for the location:

ImageIcon hi = new ImageIcon("hi.gif");

Then you draw the image with the method drawImage (you also need to use getImage on the icon). Here it is in paintComponent:
public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);     g.setColor(new Color(0,0,255));     g.setFont(new Font("Serif", Font.BOLD, 14));     g.drawString("Hello World!",100,100);     ImageIcon hi = new ImageIcon("hi.gif");     g.drawImage(hi.getImage(),0,100,null); //image, x, y, ImageObserver (ignore that, just put a 'null' there)}

This draws hi.gif just below our square.

 

VII. Conclusion

Se here's our finished program (comments removed):

import javax.swing.*;import java.awt.*;public class Graphics1 extends JPanel{     public static void main(String[] args)     {          JFrame f = new JFrame("This is the title that appears in the upper left");            f.setSize(500,500);          f.setLocation(100,100);          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          f.setContentPane(new Graphics1());          f.setVisible(true);     }     public void paintComponent(Graphics g)     {          super.paintComponent(g);          g.drawLine(0,0,100,100);          g.drawRect(0,0,100,100);          g.drawOval(0,0,100,100);          int[] xPoints = { 0, 100, 0 };          int[] yPoints = { 0, 0, 100 };          int nPoints = xPoints.length;          g.drawPolygon(xPoints, yPoints, nPoints);          g.setColor(new Color(0,0,255));          g.setFont(new Font("Serif", Font.BOLD, 14));          g.drawString("Hello World!",100,100);          ImageIcon hi = new ImageIcon("hi.gif");          g.drawImage(hi.getImage(),0,100,null);     }}
Now that you're done just hit the compile button and wait for it to finish, then run it (I have compiled this code and it runs as expected).

 

Well, I guess this tutorial is over now. I hope you enjoyed it. Perhaps I'll do another one later on double buffering and animation, but that is for another day.

 

See you when I get back from my vacation, Xisto! (or maybe earlier if this doesn't give me enough credits to last >_>)

Share this post


Link to post
Share on other sites

very nice tutorial, really long to :Preally good explained and i think members can understand it rather easy. thumbs up ;)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.