Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a Java Expert!

Join 300,406 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,663 people online right now. Registration is fast and FREE... Join Now!




Hanging Out With Applets

 
Reply to this topicStart new topic

> Hanging Out With Applets, Applet Creation, init(), paint()

Rating  5
KYA
Group Icon



post 28 Nov, 2008 - 07:13 PM
Post #1


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:

java

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:

java

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:

java

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:

java

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.

java

//”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:

java

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

<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: 1 Dec, 2008 - 07:18 PM
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

Nykc
Group Icon



post 2 Dec, 2008 - 10:37 AM
Post #2
Nice tutorial, gives me a better understanding of working with applets.

Thanks,
Go to the top of the page
+Quote Post

NeoTifa
Group Icon



post 1 Apr, 2009 - 04:45 PM
Post #3
I didn't understand a thing, yo. Are you gonna write a follow-up or something? I felt like it was cut off. sad.gif
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/7/09 10:54PM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month