Page 1 of 1

Hanging Out With Applets Applet Creation, init(), paint() Rate Topic: ***** 1 Votes

#1 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3108
  • View blog
  • Posts: 19,146
  • Joined: 14-September 07

Posted 28 November 2008 - 08:13 PM

Hanging Out With Applets

Why hi there java programmer. What brings you this way? Applets you say? Never fear we have a handy tutorial here to demystify these programs that were on the cusp of the public internet revolution in the early 1990’s.

In order to fully appreciate these special programs we must first know where they came from and what they are. Applets are traditionally java programs put into a web page. Often a game or a data selection tool of some sort, they were immensely popular when Sun introduced java as the next web technology nearly two decades ago. They have since been overtaken by other interactive web content: PHP, JSP, and the like. However many java courses still cover them and the differences between applets, console, and regular programs can trip people up.

Consider the following code segment:

public class HelloWorld {
        
    public static void main(String[] args) {
       System.out.println(">This is my first Java program in CMIS 102a\n");
       System.out.println("Hello World!");
    }
}



This is a console program. It is executed by the java virtual machine through your command line or IDE (I personally use JCreator LE, NetBeans is another favorite).

Now look at this code snippet:

public class Project
{
	public static void main(String [] args)
	{
                         //changed for example 
    		ChangeWindow window = new ChangeWindow();
    		int sentinel = 1;
    		while ((sentinel > 0) && (sentinel < 100))
    		{
    			window.gatherInput();
    		}
   	}//end main
}//end Projec



This code segment looks like a traditional console program except for, at this point in time, you may or may not know what the window object does. Let’s look at some of that code:

public class ChangeWindow extends JPanel {

	//swing components
	private JFrame frame;
	
	//variable declaration -- invariants are not accessed outside of the class,
	// only indirectly through class methods--preserves them from outside manipulation
	//whether it is intended or not
   	
	//Set up window		
   	 public ChangeWindow() 
   	 {
    		frame = new JFrame("ChangeWindow");
    	 	frame.setSize(450, 300);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.add(this);
    		setBackground(Color.WHITE);
    		frame.setVisible(true);	
   	 }
// much more stuff



The object uses GUI components to construct its frame and panel and eventually do its drawing and such. Now, don’t be alarmed if all of the above snippet makes little or no sense because with an applet you will not be using GUI components from java’s vast library of pre made usable objects. The object must call its constructor—an important distinction between a GUI program and a traditional applet. Keep that in mind.

Now consider this code segment from an applet program we will be looking at for the remainder of this tutorial:

import java.awt.*;
import java.applet.*;

public class Project extends Applet {
	
	
	public void init()
	{
		//left empty for now
	}
	public void paint(Graphics g) 
	{
		//cool paint things happen here		
	}
}



When an applet is called (in normal circumstances, by an internet browser) the init() function will be called. This method is used to initialize (get it init?) values the program may need during its lifetime. Now the other component in our applet is the paint function. This is rather self explanatory, but it is different then paint methods you may have used in GUI programs. After init() this is immediately called. You’ll have to call it again if you want a repaint (so in that regard it isn’t unlike paintComponent(), etc…)

OK enough text, let’s paint something! We’ll do a multicolored checkerboard whose size is randomized upon the beginning of the applet.

//”main” applet class
import java.awt.*;
import java.applet.*;

public class Project extends Applet {//needs to extend Applet or JApplet depending on your goals
	
	Square curSquare = new Square(); //You’ll see our square class in a second
	

	public void init()
	{
		//left empty, nothing we need to do in here
	}
	public void paint(Graphics g) 
	{
//in our square constructor we’ll rnadomize both size and pattern
		if (curSquare.pattern.toString().equals("DIAGONAL"))
		{
			curSquare.drawDiagonalSquare(g, curSquare);
		}	
		else
		{
			curSquare.drawShellSquare(g, curSquare);
		}				
	}
}



Now let’s look at our square class:

import java.lang.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.applet.*;

public class Square
{
	//Variable/enum declaration
	public enum Pattern{SHELLS,DIAGONAL};
	Pattern pattern;
	private int numRows;
    	
    	//constructor -- takes no arguments, randomly assigns pattern/number of Rows/Columns
	public Square()
	{
		//Selection Pattern
		Random generator = new Random();
		int pat = generator.nextInt(2);
		if (pat == 0)
		{
			this.pattern = pattern.SHELLS;
		}	
		else
		{
			this.pattern = pattern.DIAGONAL;
		}	
			
		//Randomize rows
		numRows = generator.nextInt(4) + 3; //(0-3) + 3 = 3-6	
	}//end constructor
	
	//Draw Diagonal Square
	public void drawDiagonalSquare(Graphics g, Square curSquare)
	{
		//Variable Declaration
		int smSquare = 21;
		int temp = smSquare;
		int count = 1, bottom = 1;
		for(int i = 1; i <= (numRows*2-1); i++)
		{
			if (i % 2 == 0)
				g.setColor(Color.RED);
			else
				g.setColor(Color.BLUE);
			
			if (i <= numRows) // first half of the cube
			{
				temp = smSquare*i;
				for(int k = 0; k < i; k++)
				{
					g.fillRect((smSquare*(k)+smSquare), temp, 20, 20);
					temp -= smSquare;
				}		
			}
			else // "back" part of the cube
			{
				temp = smSquare*numRows;
				for(int k = numRows; k > i-numRows; k--)
				{
					g.fillRect((smSquare*(count)+smSquare), temp, 20, 20);
					temp -= smSquare;
					count++;
				}
				bottom++;
				count = bottom;	
			}	
		}
}//end diagonal paint

	//Draw Shell Pattern
	public void drawShellSquare(Graphics g, Square curSquare)
	{
		int number = 1;
		int smSquare = 21;
		int x, y, temp = 0;
		//Square Drawing
		for (int shell = 1; shell <= numRows; shell++)
		{
			if (shell % 2 == 0)
				g.setColor(Color.RED);
			else
				g.setColor(Color.BLUE);
			temp = smSquare;
			for (x = 1; x < shell; x++)
			{
				if (x == 1)
					g.fillRect(smSquare, (smSquare*shell), 20,20);
				else
					g.fillRect(temp, (smSquare*shell), 20, 20);
				temp += smSquare;
			}
			temp = (smSquare*shell);	
			for (y = shell; y >= 1; y--)
			{
				g.fillRect((smSquare*shell), temp, 20, 20);
				temp -= smSquare;
			}	
		}
		}//end test shell paint
}//end Square class



Now, let’s compile and check out our creation.

Shell pattern:

Attached Image

Diagonal pattern:

Attached Image

Author’s note: the observant among us will notice that my class name does not match the one given in the code listing. That is a fact as I had used ProjectOneRevised as my initial class for this example. Be sure to compile and run and you should have no problems.

The square object will only be drawn once per execution. A fun challenge would be to allow multiple square drawing based on either the passage of time or a user action [mouse click, button, etc…]. Hopefully you learned a little about applet construction and execution today. Feel free to post questions, criticisms, concern, etc… Happy coding!


edit: Applets are run in browsers typically, but for testing purposes your IDE should create some HTML for you, if it doesn't use the following:

<html>
	<head>
	</head>
	<body bgcolor="000000">
		<center>
			<applet
				code	= "className.class"
				width	= "500"
				height	= "300"
				>
			</applet>
		</center>
	</body>
</html>



--KYA

This post has been edited by KYA: 01 December 2008 - 08:18 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Hanging Out With Applets

#2 Nykc  Icon User is offline

  • Gentleman of Leisure
  • member icon

Reputation: 731
  • View blog
  • Posts: 8,644
  • Joined: 14-September 07

Posted 02 December 2008 - 11:37 AM

Nice tutorial, gives me a better understanding of working with applets.

Thanks,
Was This Post Helpful? 0
  • +
  • -

#3 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2742
  • View blog
  • Posts: 15,834
  • Joined: 24-September 08

Posted 01 April 2009 - 05:45 PM

I didn't understand a thing, yo. Are you gonna write a follow-up or something? I felt like it was cut off. :(
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1