[JAVA]Drawing basic rectangles :)

Write your "How To" regarding anything you are comfortable with and you feel it will help the forum members.

NOTE :: All threads started here will appear only after the approval from Administrator
Post Reply
MrAlex
Posts: 188
Joined: Thu Feb 07, 2008 1:52 pm

[JAVA]Drawing basic rectangles :)

Post by MrAlex »

In this tut ill show you how to draw two basic rectangles with Java.

First we start with out imports:

Code: Select all

import java.awt.*;
import java.applet.Applet;//tells the browser its an applet lol
Now we start with the class:

Code: Select all

public class Rectangles extends Applet
       {
And then the voids:

Code: Select all

       public void paint(Graphics g) //you will always need Graphics g so the applet knows its a drawing
              {
              int left = 5;
              int top = 5;
              int width = (this.size().width) / 2 - 10; //the width of the rectangles
              int height = this.size().height - 10; //the height of the rectangles
              drawRects(g, left, top, width, height) ; //obvious what it does
              left = width + 15;
              drawFilledRects(g, left ,top, width, height); //filles the recangles
              }
       public void drawRects(Graphics g, int l, int t, int w, int h)
              {
              while (h > 0)
                    {
                    g.drawRect(l, t, w, h);
                    l += 10; //length
                    t += 10; //idk lol
                    w -= 20; //width
                    h -= 20; //height
                    }
              }
public void drawFilledRects(Graphics g, int l, int t, int w, int h)
       {
              g.setColor(Color.black); //the colour it sets - try green etc
              while (h > 0)
                    {
                    g.fillRect(l, t, w, h);
                    l += 10; //length
                    t += 10;
                    w -= 20; //width
                    h -= 20; //height
                    if (g.getColor() == Color.white) //the other colour etc
                       g.setColor(Color.black);
                    else
                       g.setColor(Color.white);
                    }
          }
}
Now you need the HTML code to run it in your browser

Code: Select all

<HTML>
<HEAD>
<TITLE>Rectangles</TITLE>
</HEAD>
<BODY>
<H1>A test page for my Java applet

</H1>
<P>
This is the output from a Java applet:



<APPLET CODE="Rectangles.class" WIDTH=150 HEIGHT=50>
</APPLET>
</BODY>
</HTML>
Now make sure you name the java file Rectangles.java!
This is what I learned from my java book (with JDK v 1.1)
Note: I posted this on other forums too ;)


Wont be back till Sunday!
Image
Post Reply