This application doesn't need a lot of sophisticated windowing techniques or controls, so it draws itself in a straightforward way using the Java Abstract Windowing Toolkit, also known as the AWT (some of the upcoming applications that need to be more powerful will use Swing). The main class in this application is Aquarium, and you need to base it on a class that can display the aquarium, which means using a class such as Frame in the AWT: import java.awt.*; public class Aquarium extends Frame { . . . This class relies on the Frame class (full name java.awt.Frame), and you can find the significant methods of this class in Table 1.1.
All this window has to do is to open when the application starts and display a background of bubbles, as shown in Figure 1.1, as well as the fish. When the Aquarium application first runs, its main method will be called, but that's a static method with many restrictions on the data you can work with, so it's a good idea to create a new Aquarium object in main, because the new object will not suffer those restrictions: import java.awt.*; public class Aquarium extends Frame { public static void main(String[] args) { new Aquarium(); } . . . } The new Aquarium object's constructor will be where the action is. In this constructor, you can set the title of the Frame window using the setTitle method, and this window will be titled "The Aquarium," as shown in Figure 1.1. To close the window, you need to catch the window close event that occurs when the user clicks the close button at upper-right corner of the window. The AWT uses listener classes to catch events such as this one. Here's how you typically handle the closing of a window, using System.exit(0) to end the application: import java.awt.*; import java.awt.event.*; public class Aquarium extends Frame { Aquarium() { setTitle("The Aquarium"); . . . this.addWindowListener(new WindowAdapter(){ public void windowClosing( WindowEvent windowEvent){ System.exit(0); } } ); } public static void main(String[] args) { new Aquarium(); } . . . } That takes care of the rudiments of creating and closing the tank in which the fish will swim. Now what about the getting the fish into the action? |