Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
AhmadLang / Introduction to Programming Using Java-1.pdf
Скачиваний:
71
Добавлен:
31.05.2015
Размер:
5.27 Mб
Скачать

CHAPTER 6. INTRODUCTION TO GUI PROGRAMMING

229

and listeners in much more detail in Section 6.3 and later sections, and I do not expect you to completely understand them at this time.)

6.2Applets and HTML

Although stand-alone applications are probably more important than applets at this (online) point in the history of Java, applets are still widely used. They can do things on Web pages

that can’t easily be done with other technologies. It is easy to distribute applets to users: The user just has to open a Web page, and the applet is there, with no special installation required (although the user must have an appropriate version of Java installed on their computer). And of course, applets are fun; now that the Web has become such a common part of life, it’s nice to be able to see your work running on a web page.

The good news is that writing applets is not much di erent from writing stand-alone applications. The structure of an applet is essentially the same as the structure of the JFrames that were introduced in the previous section, and events are handled in the same way in both types of program. So, most of what you learn about applications applies to applets, and vice versa.

Of course, one di erence is that an applet is dependent on a Web page, so to use applets e ectively, you have to learn at least a little about creating Web pages. Web pages are written using a language called HTML (HyperText Markup Language). In Subsection 6.2.3, below, you’ll learn how to use HTML to create Web pages that display applets.

6.2.1JApplet

The JApplet class (in package javax.swing) can be used as a basis for writing applets in the same way that JFrame is used for writing stand-alone applications. The basic JApplet class represents a blank rectangular area. Since an applet is not a stand-alone application, this area must appear on a Web page, or in some other environment that knows how to display an applet. Like a JFrame, a JApplet contains a content pane (and can contain a menu bar). You can add content to an applet either by adding content to its content pane or by replacing the content pane with another component. In my examples, I will generally create a JPanel and use it as a replacement for the applet’s content pane.

To create an applet, you will write a subclass of JApplet. The JApplet class defines several instance methods that are unique to applets. These methods are called by the applet’s environment at certain points during the applet’s “life cycle.” In the JApplet class itself, these methods do nothing; you can override these methods in a subclass. The most important of these special applet methods is

public void init()

An applet’s init() method is called when the applet is created. You can use the init() method as a place where you can set up the physical structure of the applet and the event handling that will determine its behavior. (You can also do some initialization in the constructor for your class, but there are certain aspects of the applet’s environment that are set up after its constructor is called but before the init() method is called, so there are a few operations that will work in the init() method but will not work in the constructor.) The other applet life-cycle methods are start(), stop(), and destroy(). I will not use these methods for the time being and will not discuss them here except to mention that destroy() is called at the end of the applet’s lifetime and can be used as a place to do any necessary cleanup, such as closing any windows that were opened by the applet.

CHAPTER 6. INTRODUCTION TO GUI PROGRAMMING

230

With this in mind, we can look at our first example of a JApplet. It is, of course, an applet that says “Hello World!”. To make it a little more interesting, I have added a button that changes the text of the message, and a state variable, currentMessage, that holds the text of the current message. This example is very similar to the stand-alone application HelloWorldGUI2 from the previous section. It uses an event-handling class to respond when the user clicks the button, a panel to display the message, and another panel that serves as a container for the message panel and the button. The second panel becomes the content pane of the applet. Here is the source code for the applet; again, you are not expected to understand all the details at this time:

import java.awt.*; import java.awt.event.*; import javax.swing.*;

/**

*A simple applet that can display the messages "Hello World"

*and "Goodbye World". The applet contains a button, and it

*switches from one message to the other when the button is

*clicked.

*/

public class HelloWorldApplet extends JApplet {

private String currentMessage = "Hello World!"; // Currently displayed message. private MessageDisplay displayPanel; // The panel where the message is displayed.

private class MessageDisplay extends JPanel { // Defines the display panel. public void paintComponent(Graphics g) {

super.paintComponent(g); g.drawString(currentMessage, 20, 30);

}

}

private class ButtonHandler implements ActionListener { // The event listener. public void actionPerformed(ActionEvent e) {

if (currentMessage.equals("Hello World!")) currentMessage = "Goodbye World!";

else

currentMessage = "Hello World!";

displayPanel.repaint(); // Paint display panel with new message.

}

}

/**

*The applet’s init() method creates the button and display panel and

*adds them to the applet, and it sets up a listener to respond to

*clicks on the button.

*/

public void init() {

displayPanel = new MessageDisplay();

JButton changeMessageButton = new JButton("Change Message"); ButtonHandler listener = new ButtonHandler(); changeMessageButton.addActionListener(listener);

JPanel content = new JPanel(); content.setLayout(new BorderLayout());

CHAPTER 6. INTRODUCTION TO GUI PROGRAMMING

231

content.add(displayPanel, BorderLayout.CENTER); content.add(changeMessageButton, BorderLayout.SOUTH);

setContentPane(content);

}

}

You should compare this class with HelloWorldGUI2.java from the previous section. One subtle di erence that you will notice is that the member variables and nested classes in this example are non-static. Remember that an applet is an object. A single class can be used to make several applets, and each of those applets will need its own copy of the applet data, so the member variables in which the data is stored must be non-static instance variables. Since the variables are non-static, the two nested classes, which use those variables, must also be non-static. (Static nested classes cannot access non-static member variables in the containing class; see Subsection 5.7.2.) Remember the basic rule for deciding whether to make a nested class static: If it needs access to any instance variable or instance method in the containing class, the nested class must be non-static; otherwise, it can be declared to be static.

6.2.2Reusing Your JPanels

Both applets and frames can be programmed in the same way: Design a JPanel, and use it to replace the default content pane in the applet or frame. This makes it very easy to write two versions of a program, one which runs as an applet and one which runs as a frame. The idea is to create a subclass of JPanel that represents the content pane for your program; all the hard programming work is done in this panel class. An object of this class can then be used as the content pane either in a frame or in an applet. Only a very simple main() program is needed to show your panel in a frame, and only a very simple applet class is needed to show your panel in an applet, so it’s easy to make both versions.

As an example, we can rewrite HelloWorldApplet by writing a subclass of JPanel. That class can then be reused to make a frame in a standalone application. This class is very similar to HelloWorldApplet, but now the initialization is done in a constructor instead of in an init() method:

import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class HelloWorldPanel extends JPanel {

private String currentMessage = "Hello World!"; // Currently displayed message. private MessageDisplay displayPanel; // The panel where the message is displayed.

private class MessageDisplay extends JPanel { // Defines the display panel. public void paintComponent(Graphics g) {

super.paintComponent(g); g.drawString(currentMessage, 20, 30);

}

}

private class ButtonHandler implements ActionListener { // The event listener. public void actionPerformed(ActionEvent e) {

if (currentMessage.equals("Hello World!")) currentMessage = "Goodbye World!";

CHAPTER 6. INTRODUCTION TO GUI PROGRAMMING

232

else

currentMessage = "Hello World!";

displayPanel.repaint(); // Paint display panel with new message.

}

}

/**

*The constructor creates the components that will be contained inside this

*panel, and then adds those components to this panel.

*/

public HelloWorldPanel() {

displayPanel = new MessageDisplay(); // Create the display subpanel.

JButton changeMessageButton = new JButton("Change Message"); // The button. ButtonHandler listener = new ButtonHandler(); changeMessageButton.addActionListener(listener);

setLayout(new BorderLayout()); // Set the layout manager for this panel. add(displayPanel, BorderLayout.CENTER); // Add the display panel. add(changeMessageButton, BorderLayout.SOUTH); // Add the button.

}

}

Once this class exists, it can be used in an applet. The applet class only has to create an object of type HelloWorldPanel and use that object as its content pane:

import javax.swing.JApplet;

public class HelloWorldApplet2 extends JApplet { public void init() {

HelloWorldPanel content = new HelloWorldPanel(); setContentPane(content);

}

}

Similarly, its easy to make a frame that uses an object of type HelloWorldPanel as its content pane:

import javax.swing.JFrame;

public class HelloWorldGUI3 {

public static void main(String[] args) { JFrame window = new JFrame("GUI Test");

HelloWorldPanel content = new HelloWorldPanel(); window.setContentPane(content); window.setSize(250,100); window.setLocation(100,100);

window.setDefaultCloseOperation( JFrame.EXIT ON CLOSE ); window.setVisible(true);

}

}

One new feature of this example is the line

window.setDefaultCloseOperation( JFrame.EXIT ON CLOSE );