YOUR FEEDBACK
Two great PDF creators
Michael Jahn wrote: related to the snapscan - are their an samples of the ...
SOA World Conference
Virtualization Conference
$50 Savings Expire May 23, 2008... – Register Today!


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
POWERBUILDER LINKS YOU MUST CLICK ON


Creating Graphical Applets

Digg This!

My last two articles focused on the fundamentals of Java and the utility that Java offers. Last month you learned how to create and run a simple applet.

This article will expand on your knowledge of applets and show you how to include GUI controls. Even simple applet development broaches many complex topics, many of which I'll briefly discuss.

Getting Started
With any Java program you first need to decide which Java packages to import. Java classes are logically grouped in related packages, unlike PowerBuilder, which doesn't embrace the concept of packaging. At first it may be difficult to determine which packages to use. With practice it'll become second nature. Major Java packages include:

  • java.applet: Classes for developing applets
  • java.awt: java.awt.event: Classes for event handling
  • javax.swing: Newer classes for GUI development
  • java.net: Classes for networking and URLs
  • java.io: Classes for input/output
  • java.lang: Basic Java functionality (this package is automatically imported)
  • java.util: Utility classes for dates and graphics
  • java.awt.image: Managing and manipulating images
Since you're programming an applet, you must import all the classes in the applet package. You're going to use GUI components and, therefore, must import all classes from the Swing package. As this applet will be using events, you must import the event classes as well. The first three lines in your program should look like the code example below:
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
Next, declare your class and give the class one method called init(). All applets include the following four methods:
public void init();
public void start();
public void stop();
public void destroy();

They have these methods because their superclass, java.applet.Applet, also includes these methods. (It has others too, but right now I just want to talk about these four.) Within the superclass, these methods are superfluous. Subclasses may override these methods to accomplish specific tasks at certain times. For example, the init() method is a good place to read parameters that were passed to the applet via HTML <PARAM> tags, because it's called exactly once when the applet starts.

However, these subclasses don't have to override the specified methods. Since they're declared in the superclass, the Web browser can invoke them as needed, without knowing whether the method is implemented in the superclass or the subclass. This is a good example of how Java employs polymorphism. Polymorphism is used identically in Java and PowerBuilder.

init(), start(), stop(), and
destroy()
The init() method is called exactly once during the life of an applet: when the applet is first loaded. It's normally used to read PARAM tags, start downloading any other images or media files you need, and set up the user interface. Most applets have init() methods.

The start() method is called at least once during the life of an applet: when the applet is started or restarted. In some cases it may be called more than once. Many applets won't have explicit start() methods and will simply inherit one from their superclass. A start() method is often used to start any threads the applet will need while it runs.

The stop() method is also called at least once during the life of an applet: when the browser leaves the page in which the applet is embedded. The applet's start() method will be called if, at some later point, the browser returns to the page containing the applet. In some cases the stop() method may be called multiple times during the course of an applet's life. Many applets you write won't have explicit stop()methods and will instead inherit one from their superclass. Your applet should use the stop() method to pause any running threads. Your applet shouldn't use any CPU cycles when stopped.

The destroy() method is called exactly once during the course of an applet's life: just before the browser unloads the applet. This method is generally used to perform any final clean-up. For example, an applet that stores a date on the server might send some data back to the server before it's terminated.

Many applets won't have explicit destroy() methods and just inherit one from their superclass. For example, in a video applet, the init() method might draw the controls and start loading the video file. The start() method would wait until the file was loaded, and then start playing it. The stop() method would pause the video, but not rewind it. If the start() method were called again, the video would pick up where it left off; it wouldn't start over from the beginning. However, if destroy() were called and then init(), the video would start over from the beginning.

In the Java Development Kit's (JDK) appletviewer, selecting the Restart menu item calls stop() and then start(). Selecting the Reload menu item calls stop(), destroy(), and init(), in that order. (Normally the byte codes will also be reloaded and the HTML file reread, though Netscape has a problem with this.)

Your own code may occasionally invoke start() and stop(). For example, it's customary to stop playing an animation when the user clicks the mouse in the applet, and restart it when they click the mouse again. Your own code can also invoke init() and destroy(), but this is normally a bad idea. Only the environment should call init() and destroy(). These applet methods act more like events. Java methods that act in this fashion are called "Java system methods" or "automatic methods".

The Basic Applet Life Cycle
You should now have a basic understanding of the various applet events. The lifecycle of an applet generally follows the steps listed below:

  1. The browser reads the HTML page and finds any <APPLET> tags.
  2. The browser parses the <APPLET> tag to find the CODE and possibly CODEBASE parameter.
  3. The browser downloads the .class file for the applet from the URL found in the last step.
  4. The browser converts the raw bytes downloaded into a Java class that is a java.lang.Class object.
  5. The browser instantiates the applet class to form an applet object.
  6. The browser calls the applet's init() method.
  7. The browser calls the applet's start() method.
  8. While the applet is running, the browser passes any events intended for the applet, such as mouse clicks, key presses, etc., to the applet's handleEvent() method. Update events are used to tell the applet that it needs to repaint itself.
  9. The browser calls the applet's stop() method.
  10. The browser calls the applet's destroy() method.
When you've reached this point, add the following lines of code to declare your class and give it an init() method:
public class FirstGUI extends Applet{
public void init(){
// I will add code here later
}
}

Using GUI Components
Like PowerBuilder, Java provides an array of controls for the user to employ. Table 1 contains Java GUI classes and their PowerBuilder equivalent. Java has other GUI components, but this list should keep you busy for a while. Notice that Java has no equivalent of an EditMask. This will become a real challenge for you later, since Java doesn't provide a simple way to validate data as the user is typing into a control. To do this you'll have to write tons of code. Also, Java has no real equivalent of the DataWindow. Java does have a control called the JTable. Like a DataWindow, this control can be used to display data in a two-dimensional format. But that's where the similarity ends. The JTable doesn't automatically keep track of row status and doesn't generate SQL.

The applet that we'll build will have three components: two buttons and a label. Add the following code to the init() method:

// Declare GUI components
JButton button1;
JButton button2;
final JLabel label1;

// Create GUI components
button1 = new JButton("Hello");
button2 = new JButton("World");
label1 = new JLabel("This is a label");

Absolute Positioning
After the GUI controls have been declared and instantiated, we'll need to determine where within the applet they'll be displayed to the user. One thing you'll have to get used to is the way Java positions and sizes controls. In PowerBuilder, placing a control on a window is no big deal. When I place a control on a window, that control will always be displayed in the same coordinates and in the same size I specify at design time. No matter what the user does to the window, the controls that I placed on it will never resize or move (unless you're using the PFC resize services). This concept is called absolute positioning: something PowerBuilder programmers take for granted.

Java doesn't work this way. Java doesn't support the concept of absolute positioning. When using GUI controls in a Java Applet/Application, Java uses something called the Layout Manager to determine where a control will be displayed and its size.

In a nutshell, Java displays controls in a relative fashion, not an absolute one. In Java, rather than specifying the absolute position for a control, you specify where controls are to be displayed relative to each other.

For example, you can specify that a button is always displayed below a text area, but you can't directly specify exactly how large each control is or where it's positioned. This takes some getting used to. If you're like me, this will drive you nuts. When learning Java, it is important to master how to use the different kinds of layout managers. This topic is beyond the scope of our immediate task and will be discussed in a later article.

There are two reasons for Java's support of relative positioning. First, since native Java isn't a GUI development tool, you can't drag-and-drop controls. All controls must be programmed manually, via Notepad or some other text editor. Second, it's impossible to predict the monitor resolution the user employs and how the users will resize your applets. If absolute positioning was used, controls may not be visible in an applet that has been made smaller.

So how do you get around this? There's a way to short-circuit the layout manager. By foregoing the use of Layout Management, you can use absolute positioning when using GUI controls. Be forewarned that using absolute positioning is a serious breach of Java programming etiquette and is seriously frowned upon by Java snobs. So enjoy yourself.

The Coordinate System
Like PowerBuilder, Java uses the standard, two-dimensional computer graphics coordinate system. The first visible pixel, in the upper left-hand corner of the applet canvas, is (0, 0). Coordinates increase to the right and down as shown in Figure 1.

Write the code to short circuit Layout Management and specify (via the setBounds() method) the x,y coordinates, as well as the width and height of each control. Add the following lines to your applet:

// Do not use layout management
this.setLayout(null);
button1.setBounds(0,100,100,50);
button2.setBounds(150,100,100,50);
label1.setBounds(80,25,200,50);

// Add the GUI components to the applet
this.add(button1);
this.add(button2);
this.add(label1);
Event Handling
PowerBuilder has spoiled us. PowerBuilder events are easy to find and code. Event-driven-programming is handled very differently in Java, which doesn't capture events unless specifically requested to do so. You must write code to tell Java which events should be trapped. Event handling in Java is performed through classes called listeners. There are many kinds of listeners and each can be associated with one or more controls. A discussion of the listener classes warrants its own series of articles.

In our applet, I want to keep track of when the user clicks either of two buttons. In PowerBuilder this will be the clicked event. Java doesn't explicitly identify such events. But Java does have a class called action listener. An action listener can be associated with a control and can be fired when some default action is performed, such as the click of a button, pressing Return, or choosing a menu item.

Each event is represented by an object providing information about that event and its source. Event sources are typically components, but other kinds of objects can also be event sources. Each event source can have multiple listeners registered upon it. Conversely, a single listener can register with multiple event sources.

Let's examine a typical event-handling scenario by looking at how the JButton handles mouse clicks. To detect when the user clicks an on-screen button (or does the keyboard equivalent), a program must have an object that implements the ActionListener interface.

The program must register this object as an action listener on the button (the event source), using the add ActionListener method. When the user clicks the on-screen button, the button fires an action event. This results in the invocation of the action listener's actionPerformed method, the only method in the ActionListener interface. The single argument to the method is an ActionEvent object, which provides information about the event and its source. Add the following lines to your applet:

// Declare a 'click' event for each of the buttons.
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
label1.setText("Hello has been clicked!");
}
});
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
label1.setText("Hello has been clicked!");
}
});
You're ready to compile and run the applet. The complete applet can be found in Code Listing 1. After you get a clean compile, create the HTML file as shown in Code Listing 2. Name the HTML file FirstGUI.htm.

Running the Applet
You should have a clean compile and be ready to run your applet. From the DOS prompt, type in AppletViewer FirstGUI.htm. Your applet should look like Figure 2.

The text should change when the buttons are clicked.

Final Thoughts
This exercise is what I call "a confidence booster". Sometimes it's important to successfully complete a new task without completely understanding how it works. That was my primary goal for this article. Obviously, applets can do much more than the one used in this example. There's a lot more to learn about applet development. Next month we'll further leverage our knowledge of PowerBuilder to learn more about applets.

About Bob Hendry
Bob Hendry is a PowerBuilder instructor for Envision Software Systems and a frequent speaker at national and international PowerBuilder conferences. He specializes in PFC development and has written two books on the subject, including Programming with the PFC 6.0.

PBDJ LATEST STORIES . . .
3rd International Virtualization Conference & Expo: Themes & Topics
From Application Virtualization to Xen, a round-up of the virtualization themes & topics being discussed in NYC June 23-24, 2008 by the world-class speaker faculty at the 3rd International Virtualization Conference & Expo being held by SYS-CON Events in The Roosevelt Hotel, in midtown
The PB Future: More on Graphs in PowerBuilder 11.5
Last week I posted a screen shot of the new 3D Rendering capabilities being added to some of the 3D graphs in PowerBuilder 11.5. It was met with mixed reviews on the PowerBuilder Futures newsgroup (forums.sybase.com) so I went back to the drawing board to see what I could come up with.
BluePhoenix Expands Modernization Collaboration with Microsoft
BluePhoenix announced that it has expanded its collaboration with Microsoft on legacy modernization projects. The collaboration provides customers moving their applications or databases to .NET-based environments the best in both modernization services and technical support. BluePhoeni
Sybase PowerBuilder Delivers AJAX and .NET Enhancements Enabling Rich Internet Application Development
Sybase announced that AJAX development capabilities and further Microsoft .NET enhancements have been added to the latest version of Sybase PowerBuilder 11, the premier 4GL rapid application development (RAD) tool. PowerBuilder 11.2 represents another milestone in the PowerBuilder road
PowerBuilder 11.2 Released: Sybase's Flagship IDE
Sybase has released the production version of its flagship .NET development tool - PowerBuilder version 11.2. This latest release of its premier IDE for RAD includes not only standard fixes but also a good list of new features. Here is the 'Coles Notes' version of these new features.
PowerBuilder Takes You To .NET
In June of 2007, Sybase released PowerBuilder 11. PowerBuilder developers can now deploy PowerBuilder components as .NET Assemblies or as .NET Web Services. A PowerBuilder developer can now create these .NET resources so that those who develop .NET solutions can benefit from PowerBuild
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING POWERBUILDER / SYBASE NEWS
Sybase and Sun Set Guinness World Record for World's Largest Data Warehouse
Sybase, Inc. (NYSE:SY), the largest enterprise software and services company exclusively