An Introduction To Java And Graphics

free web hosting
Open Discussion > CONTRIBUTE > Tutorials

An Introduction To Java And Graphics

beeseven
Table of Contents
I. Introduction
II. Before You Begin
III. Necessities in a Java Program
IV. Creating a Canvas
V. Shapes
    [/TAB]A. Line
[TAB]B. Rectangle
    [/TAB]C. Oval
[TAB]D. Polygon
VI. Other Things
    [/TAB]A. Changing the Color
[TAB]B. Strings
    [/TAB][TAB]1. Changing the Font
    [/TAB][TAB]2. Drawing a String
    C. Images
VII. Conclusion

I. Introduction
Welcome to my second tutorial here at Trap17. 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 (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:
CODE
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:
CODE
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:
CODE
import javax.swing.*; //JFrame, JPanel
import java.awt.*; //Graphics
public 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:
CODE
import javax.swing.*; //JFrame, JPanel
import java.awt.*; //Graphics
public 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:
CODE
import javax.swing.*; //JFrame, JPanel
import java.awt.*; //Graphics
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");  //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:
CODE
import javax.swing.*; //JFrame, JPanel
import java.awt.*; //Graphics
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");  //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:
CODE
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:
CODE
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":
CODE
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:
CODE
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:
CODE
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:
CODE
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:
CODE
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:
CODE
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:
CODE
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:
CODE
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:
CODE
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:
CODE
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):
CODE
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, Trap17! (or maybe earlier if this doesn't give me enough credits to last >_>)

 

 

 


Reply

OpaQue
Awesome Tutorial. Keep it up ! smile.gif

Reply

beeseven
=O Praise from OpaQue! I feel so special.

Reply

David789
Nice.

Reply

neokid
Nicly coded! I love how it has blocked spam

Reply

wassie
very nice tutorial, really long to tongue.gif
really good explained and i think members can understand it rather easy.

thumbs up smile.gif

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Recent Queries:-
  1. pcgrasp java commands - 198.52 hr back. (4)
  2. java, drawoval, application - 371.89 hr back. (1)
  3. drawpolygon in java explained - 350.65 hr back. (2)
  4. java paintcomponent paper - 426.73 hr back. (1)
  5. use g.drawrect in java using netbeans - 432.13 hr back. (1)
Similar Topics

Keywords : introduction java graphics

  1. How To Create Pdf Files Using Free Tool - Introduction to use a free tool to create PDF file (0)
  2. How To Make A Proper Introduction - Not just: Hi, I am here. (7)
    How to make a proper introduction to Trap17 forum members. FIRST OF ALL READ THE TRAP 17
    FORUM RULES AND REGULATIONS Basic Rules In-depth Regulations Trap 17 has these
    rules and regulations to maintain some kind of order in this chaotic world; to keep the forum
    refreshing and informative, uncluttered by useless, redundant chatter. PLEASE follow them. After
    all this is all for FREE and keeps Trap 17 up and running. Who are you? (You
    needn't use your legal name, but give us something to call you that is an indicator of you...
  3. Making a java based program - (3)
    Java GUI Making a Little Java Program Sec. 1: Imports and starting it off Sec. 2: Variables Sec.
    3: Frame and Stuff Sec. 4: Declaring buttons Sec. 5: Adding buttons Sec. 6: Action Listening Sec. 7:
    Using this for a learning experience Section 1 Now, let's think. What imports do we need? We
    obviously need GUI imports. We also need the action Listener. So, let's declare this at the very
    top: Code: CODE import java.awt.*; import java.awt.event.*; import javax.swing.*; That's
    all we need to get all our supplies. Now to start us off. Skip a couple lines ...
  4. A Little Introduction To 3d Studio Max - How to make a simple abstract image (9)
    This tutorial will teach you the basics of making abstract images in 3D studio max. In this example,
    I used a simple sphere, and applied the “Noise” modifier. Then, I applied a transparent, blue,
    plastic-like material to spice up the whole thing. Let’s start. First, make a sphere by selecting
    the “Sphere” button in the “Standard Primitives” section, and draw somewhere in the center of the
    perspective view. We will set the size of the sphere later on. The sphere I made looks like this,
    yours can be different in size and color, but the only thing that is important is to...
  5. Building An Address Book With Java - (1)
    Dear Friends I am sharing a java program with all of u which I built a few years back. I guess it
    will help beginners. It uses java utill package to store data in a flat file. The File
    Name-----phone.java import java .io .*; import java .util .*; import java.awt.event.*; public
    class phone { public void new_record() { String id,name,city,add,number,total,list;
    boolean bln=false; try { Properties pr=new Properties(); FileInputStream
    fin=new FileInputStream("phone.dat"); if(fin!=null) { pr.load(fin); }...
  6. Introduction To Templating - Templating your website with PHP (1)
    Pre-note Hello and welcome. if your website doesn't use a templating function, you may have
    noticed it's pretty hard to update your website (layout) unless you dig through many files to
    update the images and such. The solution is templates. If you ever got curious and looked into
    phpBB codes or any other template based forum/CMS, you saw the .tpl files they use. I am not at a
    point where i base everything on .tpl (simply because i havent taken the time to see how it all
    works). But i do can tell you that it's the same principle, template your site using an...
  7. Php Sockets - Introduction to an underused function of PHP (4)
    This tutorial is based on a question written in the PHP programming board Inspiration
    Introduction Sockets, an underused function in PHP, is a function that enables you to open
    connection to other peoples computers and vice versa. By sending commands to the operating server,
    it will first see if there's response, then, it sends or receives data that the operating server
    has available. Creation of a socket Of course, a first step in using sockets, is creating it,
    this is done by: CODE resource socket_create ( int domain, int type, int protocol) ...



Looking for introduction, java, graphics

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for introduction, java, graphics

*MORE FROM TRAP17.COM*
advertisement



An Introduction To Java And Graphics



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE