Creating AWT apps

The Abstract Windowing Toolkit, or AWT, was Java's early attempt at a GUI toolkit. It's still supported and used, so we'll take a look at an example here that will launch its own window. The original AWT package only took six weeks to write, and the controls, designed for use in applets, were modeled after HTML controls. Since that time, Swing has taken over the standard Java interface—but even Swing is built on top of AWT. Our AWT example will just launch its own window and display the same message as our applet. To follow along, create a new project, Ch06_02, and give it a new class with a main method, Ch06_02, putting that class into the org.eclipsebook.ch06 package. We need to import java.awt.* for basic AWT support, and java.awt.event.* to handle the window-closing event, so add this code:

import java.awt.*;
import java.awt.event.*;


The actual window this example will display will be based on the AWT Frame class and will be called AppFrame, so add this code to Ch06_02.java:

class AppFrame extends Frame
{
 .
 .
 .
}


As in our applet, we'll override the paint method and use the passed Graphics object to display the text we want in the new window:

class AppFrame extends Frame
{
 public void paint(Graphics g)
 {
 g.drawString("Hello from Eclipse!", 60, 100);
 }
}


Now, in the Ch06_02 class's main method, we'll create a new window of the AppFrame class and set its size:

public class Ch06_02 {
 public static void main(String [] args)
 {
 AppFrame f = new AppFrame( );
 f.setSize(200, 200);
 .
 .
 .
 }
}


All that's left is to add the standard code to handle the window-close event that occurs when the user clicks the X button in the window at the upper right, and to show the window using its show method:

public class Ch06_02 {
 public static void main(String [] args)
 {
 AppFrame f = new AppFrame( );
 f.setSize(200, 200);
 f.addWindowListener(new WindowAdapter( ) { public void
 windowClosing(WindowEvent e) {System.exit(0);}});
 f.show( );
 }
}


To run this app, select Run AsScreenshot Java app. This app will launch the AWT window, complete with the message you see in Screenshot-3.

Screenshot-3. Running a windowed AWT app
Java figs/ecps_0603.gif

And that's it—the code for this app appears in Example 6-2.

Example 6-2. A basic AWT app
package org.eclipsebook.ch06;
import java.awt.*;
import java.awt.event.*;
public class Ch06_02 {
 public static void main(String [] args)
 {
 AppFrame f = new AppFrame( );
 f.setSize(200, 200);
 f.addWindowListener(new WindowAdapter( ) { public void
 windowClosing(WindowEvent e) {System.exit(0);}});
 f.show( );
 }
}
class AppFrame extends Frame
{
 public void paint(Graphics g)
 {
 g.drawString("Hello from Java!", 60, 100);
 }
}


As you can see, launching windowed apps this way is no problem from Eclipse—just set up your app to launch windows and run it. AWT is fine up to a point, but Swing is where the action is today.

      
Comments