Jump to content
xisto Community
Sign in to follow this  
DarkDivinity

Drawing Basic Rectangles Using Java

Recommended Posts

I posted on another forums... But not allowed to post links ^_^

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

First we start with out imports:

import java.awt.*;import java.applet.Applet;//tells the browser its an applet lol
Now we start with the class:
public class Rectangles extends Applet	   {
And then the voids:

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
<HTML>
<HEAD>
<TITLE>Rectangles</TITLE>
</HEAD>
<BODY>
<H1>A test page for my Java applet<BR>
</H1>
<P>
This is the output from a Java applet:<BR>
<BR>
<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)
Also Read the comments I have added to help you out!

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.