Tải bản đầy đủ (.pdf) (187 trang)

Advanced Java 2 Platform HOW TO PROGRAM phần 3 ppsx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.94 MB, 187 trang )

312 Case Study: Java 2D GUI Application with Design Patterns Chapter 5
147 menuBar.add( fileMenu );
148 menuBar.add( helpMenu );
149
150 // set Frame's JMenuBar
151 setJMenuBar( menuBar );
152
153 // create application JToolBar
154 toolBar = new JToolBar();
155
156 // disable JToolBar floating
157 toolBar.setFloatable( false );
158
159 // add New Drawing and Open Drawing actions to JToolBar
160 toolBar.add( newAction );
161 toolBar.add( openAction );
162
163 toolBar.addSeparator();
164
165 // add Exit action to JToolBar
166 toolBar.add( exitAction );
167
168 toolBar.addSeparator();
169
170 // add About action to JToolBar
171 toolBar.add( aboutAction );
172
173 // add toolBar and desktopPane to ContentPane
174 getContentPane().add( toolBar, BorderLayout.NORTH );
175 getContentPane().add( desktopPane, BorderLayout.CENTER );
176


177 // add WindowListener for windowClosing event
178 addWindowListener(
179 new WindowAdapter() {
180
181 public void windowClosing( WindowEvent event )
182 {
183 exitApplication();
184 }
185 }
186 );
187
188 // wait for SplashScreen to go away
189 while ( splashScreen.isVisible() ) {
190
191 try {
192 Thread.sleep( 10 );
193 }
194
195 // handle exception
196 catch ( InterruptedException interruptedException ) {
197 interruptedException.printStackTrace();
198 }
Fig. 5.28
Fig. 5.28Fig. 5.28
Fig. 5.28
DeitelDrawing application that uses a multiple-document interface
for displaying and modifying
DeitelDrawing drawings (part 4 of 8).
Chapter 5 Case Study: Java 2D GUI Application with Design Patterns 313
199 }

200
201 // set initial JFrame size
202 setSize( 640, 480 );
203
204 // position application window
205 centerWindowOnScreen();
206
207 // make application visible
208 setVisible( true );
209
210 // create new, empty drawing window
211 createNewWindow();
212
213 } // end DeitelDrawing constructor
214
215 // create new DrawingInternalFrame
216 private DrawingInternalFrame createNewWindow()
217 {
218 // create new DrawingInternalFrame
219 DrawingInternalFrame frame =
220 new DrawingInternalFrame( "Untitled Drawing" );
221
222 // add listener for InternalFrame events
223 frame.addInternalFrameListener(
224 new DrawingInternalFrameListener() );
225
226 // make DrawingInternalFrame opaque
227 frame.setOpaque( true );
228
229 // add DrawingInternalFrame to desktopPane

230 desktopPane.add( frame );
231
232 // make DrawingInternalFrame visible
233 frame.setVisible( true );
234
235 // select new DrawingInternalFrame
236 try {
237 frame.setSelected( true );
238 }
239
240 // handle exception selecting DrawingInternalFrame
241 catch ( PropertyVetoException vetoException ) {
242 vetoException.printStackTrace();
243 }
244
245 // return reference to newly created DrawingInternalFrame
246 return frame;
247 }
248
249 // InternalFrameAdapter to listen for InternalFrame events
Fig. 5.28
Fig. 5.28Fig. 5.28
Fig. 5.28
DeitelDrawing application that uses a multiple-document interface
for displaying and modifying
DeitelDrawing drawings (part 5 of 8).
314 Case Study: Java 2D GUI Application with Design Patterns Chapter 5
250 private class DrawingInternalFrameListener
251 extends InternalFrameAdapter {
252

253 // when DrawingInternalFrame is closing disable
254 // appropriate Actions
255 public void internalFrameClosing(
256 InternalFrameEvent event )
257 {
258 DrawingInternalFrame frame =
259 ( DrawingInternalFrame ) event.getSource();
260
261 // frame closes successfully, disable Save menu items
262 if ( frame.close() ) {
263 saveMenuItem.setAction( null );
264 saveAsMenuItem.setAction( null );
265 }
266 }
267
268 // when DrawingInternalFrame is activated, make its JToolBar
269 // visible and set JMenuItems to DrawingInternalFrame Actions
270 public void internalFrameActivated(
271 InternalFrameEvent event )
272 {
273 DrawingInternalFrame frame =
274 ( DrawingInternalFrame ) event.getSource();
275
276 // set saveMenuItem to DrawingInternalFrame's saveAction
277 saveMenuItem.setAction( frame.getSaveAction() );
278 saveMenuItem.setIcon( null );
279
280 // set saveAsMenuItem to DrawingInternalFrame's
281 // saveAsAction
282 saveAsMenuItem.setAction( frame.getSaveAsAction() );

283 saveAsMenuItem.setIcon( null );
284 }
285 }
286
287 // close each DrawingInternalFrame to let user save drawings
288 // then exit application
289 private void exitApplication()
290 {
291 // get array of JInternalFrames from desktopPane
292 JInternalFrame frames[] = desktopPane.getAllFrames();
293
294 // keep track of DrawingInternalFrames that do not close
295 boolean allFramesClosed = true;
296
297 // select and close each DrawingInternalFrame
298 for ( int i = 0; i < frames.length; i++ ) {
299 DrawingInternalFrame nextFrame =
300 ( DrawingInternalFrame ) frames[ i ];
301
Fig. 5.28
Fig. 5.28Fig. 5.28
Fig. 5.28
DeitelDrawing application that uses a multiple-document interface
for displaying and modifying
DeitelDrawing drawings (part 6 of 8).
Chapter 5 Case Study: Java 2D GUI Application with Design Patterns 315
302 // select current DrawingInternalFrame
303 try {
304 nextFrame.setSelected( true );
305 }

306
307 // handle exception when selecting DrawingInternalFrame
308 catch ( PropertyVetoException vetoException ) {
309 vetoException.printStackTrace();
310 }
311
312 // close DrawingInternalFrame and update allFramesClosed
313 allFramesClosed = allFramesClosed && nextFrame.close();
314 }
315
316 // exit application only if all frames were closed
317 if ( allFramesClosed )
318 System.exit( 0 );
319
320 } // end method exitApplication
321
322 // display application's splash screen
323 public void showSplashScreen()
324 {
325 // create ImageIcon for logo
326 Icon logoIcon = new ImageIcon(
327 getClass().getResource( "images/deitellogo.png" ) );
328
329 // create new JLabel for logo
330 JLabel logoLabel = new JLabel( logoIcon );
331
332 // set JLabel background color
333 logoLabel.setBackground( Color.white );
334
335 // set splash screen border

336 logoLabel.setBorder(
337 new MatteBorder( 5, 5, 5, 5, Color.black ) );
338
339 // make logoLabel opaque
340 logoLabel.setOpaque( true );
341
342 // create SplashScreen for logo
343 splashScreen = new SplashScreen( logoLabel );
344
345 // show SplashScreen for 3 seconds
346 splashScreen.showSplash( 3000 );
347
348 } // end method showSplashScreen
349
350 // center application window on user's screen
351 private void centerWindowOnScreen()
352 {
353 // get Dimension of user's screen
Fig. 5.28
Fig. 5.28Fig. 5.28
Fig. 5.28
DeitelDrawing application that uses a multiple-document interface
for displaying and modifying
DeitelDrawing drawings (part 7 of 8).
316 Case Study: Java 2D GUI Application with Design Patterns Chapter 5
Method createNewWindow (lines 216–247) creates a new DrawingInternal-
Frame. Inner class DrawingInternalFrameListener (lines 250–285) listens for
internalFrameClosing and internalFrameActivated messages. The Deitel
Drawing application’s File menu contains JMenuItems for saving the currently active
drawing. When a DrawingInternalFrame closes, lines 263–264 remove that Draw-

ingInternalFrame’s saveAction and saveAsAction from saveMenuItem
and saveAsMenuItem. When a DrawingInternalFrame is activated, lines 277–
283 invoke method setAction of class JMenuItem to set the Actions for save-
MenuItem and saveAsMenuItem.
Method exitApplication (lines 289–320) prompts the user to save any unsaved
drawings before the application exits. Line 292 invokes method getAllFrames of class
JDesktopPane to retrieve an array of JInternalFrames in the application. Line 313
invokes method close of class DrawingInternalFrame to attempt to close each
DrawingInternalFrame in the array. Method close returns true if the Draw-
ingInternalFrame closed successfully, false otherwise. Line 313 accumulates the
results of closing each DrawingInternalFrame in boolean allFramesClosed.
If all DrawingInternalFrames close successfully, line 318 exits the application. If
any DrawingInternalFrame did not close, the application assumes that the user can-
celled the request to close the application.
The Deitel Drawing application displays the Deitel logo in a SplashScreen
(Fig. 5.29) while the application loads. The SplashScreen constructor (lines 19–58)
takes as an argument the Component to display. Line 22 creates JWindow (a borderless
window) in which to display the given component. Lines 46–56 center the Splash-
Screen’s JWindow on the user’s screen.
354 Dimension screenDimension =
355 Toolkit.getDefaultToolkit().getScreenSize();
356
357 // use screen width and height and application width
358 // and height to center application on user's screen
359 int width = getSize().width;
360 int height = getSize().height;
361 int x = ( screenDimension.width - width ) / 2 ;
362 int y = ( screenDimension.height - height ) / 2 ;
363
364 // place application window at screen's center

365 setBounds( x, y, width, height );
366 }
367
368 // execute application
369 public static void main( String args[] )
370 {
371 new DeitelDrawing();
372 }
373 }
Fig. 5.28
Fig. 5.28Fig. 5.28
Fig. 5.28
DeitelDrawing application that uses a multiple-document interface
for displaying and modifying
DeitelDrawing drawings (part 8 of 8).
Chapter 5 Case Study: Java 2D GUI Application with Design Patterns 317
1 // SplashScreen.java
2 // SplashScreen implements static method showSplash for
3 // displaying a splash screen.
4 package com.deitel.advjhtp1.drawing;
5
6 // Java core packages
7 import java.awt.*;
8 import java.awt.event.*;
9
10 // Java extension packages
11 import javax.swing.*;
12
13 public class SplashScreen {
14

15 private JWindow window;
16 private Timer timer;
17
18 // SplashScreen constructor
19 public SplashScreen( Component component )
20 {
21 // create new JWindow for splash screen
22 window = new JWindow();
23
24 // add provided component to JWindow
25 window.getContentPane().add( component );
26
27 // allow user to dismiss SplashScreen by clicking mouse
28 window.addMouseListener(
29
30 new MouseAdapter() {
31
32 // when user presses mouse in SplashScreen,
33 // hide and dispose JWindow
34 public void mousePressed( MouseEvent event ) {
35 window.setVisible( false );
36 window.dispose();
37 }
38 }
39
40 ); // end call to addMouseListener
41
42 // size JWindow for given Component
43 window.pack();
44

45 // get user's screen size
46 Dimension screenDimension =
47 Toolkit.getDefaultToolkit().getScreenSize();
48
49 // calculate x and y coordinates to center splash screen
50 int width = window.getSize().width;
51 int height = window.getSize().height;
52 int x = ( screenDimension.width - width ) / 2 ;
Fig. 5.29
Fig. 5.29Fig. 5.29
Fig. 5.29
SplashScreen class for displaying a logo while the application loads
(part 1 of 2).
318 Case Study: Java 2D GUI Application with Design Patterns Chapter 5
53 int y = ( screenDimension.height - height ) / 2 ;
54
55 // set the bounds of the window to center it on screen
56 window.setBounds( x, y, width, height );
57
58 } // end SplashScreen constructor
59
60 // show splash screen for given delay
61 public void showSplash( int delay ) {
62
63 // display the window
64 window.setVisible( true );
65
66 // crate and start a new Timer to remove SplashScreen
67 // after specified delay
68 timer = new Timer( delay,

69 new ActionListener() {
70
71 public void actionPerformed( ActionEvent event )
72 {
73 // hide and dispose of window
74 window.setVisible( false );
75 window.dispose();
76 timer.stop();
77 }
78 }
79 );
80
81 timer.start();
82
83 } // end method showSplash
84
85 // return true if SplashScreen window is visible
86 public boolean isVisible()
87 {
88 return window.isVisible();
89 }
90 }
Fig. 5.29
Fig. 5.29Fig. 5.29
Fig. 5.29 SplashScreen class for displaying a logo while the application loads
(part 2 of 2).
Chapter 5 Case Study: Java 2D GUI Application with Design Patterns 319
Method showSplash (lines 61–83) takes as an integer argument the number of mil-
liseconds for which to display the SplashScreen. Line 64 makes the JWindow visible,
and line 51 causes the current Thread to sleep for the given delay. After the delay

expires, lines 60–61 hide and dispose of the JWindow.
In this chapter, we presented a substantial application that used the MVC architecture
and many popular design patterns, including Observer, Factory Method, Template Method,
State and Command. We also demonstrated how applications can store and retrieve infor-
mation in XML documents. Our drawing application takes advantage of the rich set of GUI
components offered by Swing and the powerful drawing capabilities offered by Java 2D.
Drag-and-drop functionality enables users to transfer shapes between drawings and add
their own images.
Throughout the rest of the book, we use design patterns and the MVC architecture to
build substantial examples and case studies. For example, the Enterprise Java case study of
Chapters 17–20 presents an online bookstore that uses the MVC architecture.
SELF-REVIEW EXERCISES
5.1 Which part of the model-view-controller architecture processes user input? Which Deitel
Drawing classes implement this part of MVC?
5.2 What interface must a class implement to enable data transfer using drag and drop for in-
stances of that class?
5.3 In general, how does a user begin a drag-and-drop operation? Give an example.
5.4 What type of object notifies a DragGestureListener that the user made a drag gesture?
5.5 How can a DropTargetListener or DragSourceListener determine what type of
data a Transferable object contains?
ANSWERS TO SELF-REVIEW EXERCISES
5.1 The controller in MVC processes user input. In the Deitel Drawing application, MyShape-
Controller subclasses process user input via the mouse. Class DragAndDropController
processes user input via drag-and-drop operations.
5.2 A class that supports drag and drop must implement interface Transferable.
5.3 A user begins a drag-and-drop operation by making a drag gesture. For example, on the Win-
dows platform, a user makes a drag gesture by pressing the mouse button on a draggable object and
dragging the mouse.
5.4 A DragGestureRecognizer issues a DragGestureEvent to notify a DragGes-
tureListener that the user made a drag gesture.

5.5 Method getTransferDataFlavors of interface Transferable returns an array of
DataFlavor objects. Each DataFlavor has a MIME type that describes the type of data the
Transferable object supports.
EXERCISES
5.6 Create class RotatingDrawingView that extends class DrawingView and uses Java
2D transformations (Chapter 4) to display the drawing rotated by ninety degrees.
5.7 Modify your solution to Exercise 5.6 to use a and a java.awt.Timer to continually rotate
the drawing in five-degree increments.
320 Case Study: Java 2D GUI Application with Design Patterns Chapter 5
5.8 Create class RandomMyShapeController that extends class MyShapeController
and adds random MyShape subclasses with random sizes, colors and other properties to the Draw-
ingModel. In method startShape, class RandomMyShapeController should prompt the
user for the number of random shapes to add to the drawing. Create a new MyShapeController-
Factory subclass (Fig. 5.18) named RandomMyShapeControllerFactory that constructs a
RandomMyShapeController when the String "Random" is passed to method newMy-
ShapeController. [Hint: Be sure to override method getSupportedShapes of class My-
ShapeControllerFactory to return a String array that includes the String "Random".]
6
JavaBeans Component
Model
Objectives
• To understand JavaBeans and how they facilitate
component-oriented software construction.
• To be able to use Forte for Java Community Edition to
build JavaBeans-based applications.
• To be able to wrap class definitions as JAR files for
use as JavaBeans and stand-alone applications.
• To be able to define JavaBean properties and events.
Mirrors should reflect a little before throwing back images.
Jean Cocteau

Television is like the invention of indoor plumbing. It didn’t
change people’s habits. It just kept them inside the house.
Alfred Hitchcock
The power of the visible is the invisible.
Marianne Moore
The sun has a right to "set" where it wants to, and so, I may
add, has a hen.
Charles Farrar Browne
The causes of events are ever more interesting than the
events themselves.
Marcus Tullius Cicero
…the mechanic that would perfect his work must first
sharpen his tools.
Confucius
322 JavaBeans Component Model Chapter 6
6.1 Introduction
This chapter presents Java’s reusable software component model: JavaBeans. JavaBeans (of-
ten called beans) allow developers to reap the benefits of rapid application development in
Java by assembling predefined software components to create powerful applications and ap-
plets. Graphical programming and design environments (often called builder tools, IDEs or
integrated development environments) that support beans provide programmers with tremen-
dous flexibility by allowing programmers to reuse and integrate existing disparate compo-
nents that, in many cases, were never intended to be used together. These components can be
linked together to create applets, applications or even new beans for reuse by others.
JavaBeans and other component-based technologies have led to a new type of pro-
grammer, the component assembler, who uses well-defined components to create more
robust functionality. Component assemblers do not need to know the implementation
details of components. Rather, they need to know what services the components provide,
so they can have other components interact with them.
As an example of the concept of beans, assume that a component assembler has an ani-

mation bean that has methods to startAnimation and stopAnimation. The com-
ponent assembler may want to provide two buttons, one that will start the animation and
one that will stop the animation (an example you will see later in this chapter). With beans,
we can simply “connect” one button to the animation’s startAnimation method and
connect another button to the animation’s stopAnimation method, such that when the
user clicks a button, the appropriate method of the animation bean is called. The builder
tool does all the work of associating the button-click event with the appropriate method to
call on the animation bean. All the programmer needs to do is tell the builder tool which
two components to “connect.”
The benefit of beans in this example is that the animation bean and the button beans do
not need to know about each other before they are assembled in a builder tool. Someone
else can be responsible for defining the concept of a button in a reusable manner (e.g.,
Outline
6.1 Introduction
6.2 Using Beans in Forte for Java Community Edition
6.3 Preparing a Class to be a JavaBean
6.4 Creating a JavaBean: Java Archive Files
6.5 JavaBean Properties
6.6 Bound Properties
6.7 Indexed Properties and Custom Events
6.8 Customizing JavaBeans for Builder Tools
6.8.1 PropertyEditors
6.8.2 Customizers
6.9 Internet and World Wide Web Resources
Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises
Chapter 6 JavaBeans Component Model 323
javax.swing.JButton). A button is not specific to our example. Rather, it is a com-
ponent used in many applications and applets. When the user of a program clicks a button,
the user expects an action specific to that program to occur. (Some buttons, such as OK but-
tons, typically have the same meaning in all programs.) However, the basic concept of a

button—how it is displayed, how it works and how it notifies other components that it was
clicked—is the same in every application (although we typically customize the button’s
label). The component assembler’s job is not to create the concept of a button, but rather to
use the preexisting button component to provide functionality to the user of the program.
Component assemblers can make beans communicate through the beans’ well-defined
services (i.e., methods), typically without writing any code (the builder tool often generates
the code, which is sometimes hidden from the component assembler—depending on the
tool). Indeed, a component assembler often can create complex applications literally by
"connecting the dots."
In this chapter, we show you how to use existing beans and how to create your own
basic beans. After studying this chapter, you will have a foundation in JavaBeans program-
ming that will enable you to develop applications and applets rapidly using the more
advanced features of integrated development environments that support beans. You will
also have a solid foundation for further study of JavaBeans.
For more JavaBeans information, visit the Sun Microsystems Web site for JavaBeans:
java.sun.com/beans/
This site provides a complete set of resources for learning about and using JavaBeans.
6.2 Using Beans in Forte for Java Community Edition
Sun Microsystem’s Forte for Java Community Edition (Fig. 6.1) is an integrated develop-
ment environment that provides a builder tool for assembling JavaBeans. Forte provides vi-
sual access to a variety of JavaBeans and allows you to install and manipulate additional
beans. In this section, we demonstrate how to use existing beans in Forte. Later in the chap-
ter, we rely on your knowledge of this section to use the beans created in this chapter. We
assume you are already familiar with the basic operation of Forte. For details on getting
started with Forte, visit the resources for this book on our Web site, www.deitel.com.
There, we have a “Getting Started with Forte for Java Community Edition 2.0” tutorial.
Software Engineering Observation 6.1
A benefit of working in a bean-ready development environment is that the environment visu-
ally presents the properties of the bean to the programmer for easy modification and custom-
ization of the bean at design time.

6.1
A bean must be installed before it is manipulated in Forte. Click the Tools menu and
select Install New JavaBean (Fig. 6.2). A file dialog box labelled Install JavaBean
appears (Fig. 6.3). Copy LogoAnimator.jar from the CD-ROM that accompanies this
book. The next dialog box lists the JavaBeans within the selected JAR file (Fig. 6.4). Select
LogoAnimator and click the OK button (Fig. 6.4). Select Beans in the Palette Cat-
egory dialog box that appears next and click OK (Fig. 6.4). Clicking the Beans tab in the
Component Palette shows a question mark icon (Fig. 6.5). Moving the mouse over the
icon in the Component Palette displays a tool tips showing that the icon represents the
LogoAnimator JavaBean (Fig. 6.5).
324 JavaBeans Component Model Chapter 6
Fig. 6.1
Fig. 6.1Fig. 6.1
Fig. 6.1 Forte for Java Community Edition 2.0.
Fig. 6.2
Fig. 6.2Fig. 6.2
Fig. 6.2 Install New JavaBean menu item.
Fig. 6.3
Fig. 6.3Fig. 6.3
Fig. 6.3 Install JavaBean dialog.
Chapter 6 JavaBeans Component Model 325
GUI JavaBeans must be added to a Java Container to be able to use the builder tool
to edit the bean properties or to link the beans to other components. To demonstrate adding
and manipulating JavaBeans, we open a JFrame. Select the Filesystems tab in the
Explorer window (Fig. 6.6). Select the Development directory (Fig. 6.7). Select New
from the File menu (Fig. 6.8). In the Template Chooser (Fig. 6.9), expand the Swing
Forms option and select JFrame. Enter “AnimationWindow” in the Name: field
(Fig. 6.9). Click Finish to create the new JFrame.
Fig. 6.4
Fig. 6.4Fig. 6.4

Fig. 6.4 Select JavaBean and Palette Category dialogs.
Fig. 6.5
Fig. 6.5Fig. 6.5
Fig. 6.5 Beans tab in the Component Palette and tooltip for LogoAnimator
JavaBean.
Fig. 6.6
Fig. 6.6Fig. 6.6
Fig. 6.6 Filesystems tab in the Explorer window.
Component Palette
326 JavaBeans Component Model Chapter 6
The new AnimationWindow class appears inside the Filesystems field of the
Explorer. The Component Inspector, Form and Source Editor windows should all
appear (Fig. 6.10). The Component Inspector (Fig. 6.11) lists all the visual and nonvi-
sual components within AnimationWindow and also shows the property sheet for
selected components (we will discuss the property sheet later). The Form window
(Fig. 6.11) shows the JFrame with its current layout and components. The Source
Fig. 6.7
Fig. 6.7Fig. 6.7
Fig. 6.7 Development directory selected in Explorer window.
Fig. 6.8
Fig. 6.8Fig. 6.8
Fig. 6.8 New menu item.
Fig. 6.9
Fig. 6.9Fig. 6.9
Fig. 6.9 New Template Chooser dialog.
Chapter 6 JavaBeans Component Model 327
Editor (Fig. 6.12) shows the Java source code Forte generates. Forte updates this code as
components and events are added, deleted and changed.
Fig. 6.10
Fig. 6.10Fig. 6.10

Fig. 6.10 GUI Editing tab of Forte.
Fig. 6.11
Fig. 6.11Fig. 6.11
Fig. 6.11 Component Inspector and Form windows.
328 JavaBeans Component Model Chapter 6
We now begin building the application by placing the LogoAnimator JavaBean we
just imported into the AnimationWindow. Click the Beans tab of the Component
Palette (Fig. 6.13). Next, click the LogoAnimator icon (Fig. 6.14). Then, click in the
Form window in the center of the JFrame. A spinning animation of the Deitel and Asso-
ciates, Inc., logo will appear in the window (Fig. 6.15).
Fig. 6.12
Fig. 6.12Fig. 6.12
Fig. 6.12 Source Editor window.
Fig. 6.13
Fig. 6.13Fig. 6.13
Fig. 6.13 Beans tab of the Component Palette.
Fig. 6.14
Fig. 6.14Fig. 6.14
Fig. 6.14 LogoAnimator icon.
Chapter 6 JavaBeans Component Model 329
The property sheet in the Component Inspector displays a component’s properties
and allows them to be edited. Click the LogoAnimator in the Form window. Blue
squares appear at the corners of the animation to show it is selected (Fig. 6.15). The Com-
ponent Inspector shows all the LogoAnimator properties (Fig. 6.16). Many of the
properties are inherited from JPanel, the superclass of LogoAnimator. The back-
ground property shows a swatch of color and a name indicating the LogoAnimator
background color. Click the color, and a drop-down menu appears (Fig. 6.17). It lists some
of the predefined colors in Java. Select the first color listed in the drop-down menu to
change the LogoAnimator’s background to white (Fig. 6.18). Try selecting other colors
to get used to changing JavaBean properties.

Fig. 6.15
Fig. 6.15Fig. 6.15
Fig. 6.15 LogoAnimator animation in the Form window.
Fig. 6.16
Fig. 6.16Fig. 6.16
Fig. 6.16 Component Inspector with LogoAnimator Properties sheet.
330 JavaBeans Component Model Chapter 6
In addition to changing JavaBean properties with the builder tool, component assem-
blers can connect JavaBeans with events. For instance, a button can control the function of
another component. We demonstrate this with buttons that start and stop the LogoAni-
mator’s animation.
Fig. 6.17
Fig. 6.17Fig. 6.17
Fig. 6.17 Component Inspector drop down-menu for the background property.
Fig. 6.18
Fig. 6.18Fig. 6.18
Fig. 6.18 Changing background color of LogoAnimator.
Chapter 6 JavaBeans Component Model 331
Before adding other components to our example, we change the window’s layout to a
FlowLayout. In the Explorer window, expand the AnimationWindow node
(Fig. 6.19). Right click the JFrame node, select Set Layout and click FlowLayout
(Fig. 6.20).
Select the Swing tab in the Component Palette (Fig. 6.21). This tab contains the
most common Swing components. The second component in the list is the JButton
(Fig. 6.22). Click the JButton icon, then click an empty spot in the Form that contains
the LogoAnimator. A new JButton appears in the window next to the LogoAni-
mator (Fig. 6.23). Select the JButton and locate the text property in the Compo-
nent Inspector. Click the text field, type Start Animation (Fig. 6.24), then press
Enter. The button text in the Form will change to the new value (Fig. 6.24). Repeat this
procedure to add another JButton with the text Stop Animation.

Fig. 6.19
Fig. 6.19Fig. 6.19
Fig. 6.19 AnimationWindow selected in Explorer.
Fig. 6.20
Fig. 6.20Fig. 6.20
Fig. 6.20 Selecting FlowLayout in the Explorer menu.
332 JavaBeans Component Model Chapter 6
Fig. 6.21
Fig. 6.21Fig. 6.21
Fig. 6.21 Swing tab of the Component Palette.
Fig. 6.22
Fig. 6.22Fig. 6.22
Fig. 6.22 JButton icon in the Component Palette.
Fig. 6.23
Fig. 6.23Fig. 6.23
Fig. 6.23 Adding a JButton to AnimationWindow.
Fig. 6.24
Fig. 6.24Fig. 6.24
Fig. 6.24 Editing text property of JButton.
Chapter 6 JavaBeans Component Model 333
Next, we connect the Start Animation and Stop Animation buttons to the Logo-
Animator so the user can start and stop the animation. The button with the mouse pointer
icon to the left of the Component Palette enables Selection Mode (Fig. 6.25). This
mode enables Forte users to select components in a Form window. The button with the
double-arrows icon below the Selection Mode icon enables Connection Mode
(Fig. 6.26), which allows Forte users to connect components with a wizard that generates
code in the Source Editor. Click the Connection Mode icon to enter Connection
Mode (Fig. 6.27). Click the Start Animation JButton (Fig. 6.28), which will be the
source of the event (i.e., the source component) that starts the animation. Red squares appear
at the corners of the JButton. Next, click the LogoAnimator. Red squares also appear at

the corners of LogoAnimator and the Connection Wizard dialog appears (Fig. 6.29).
Step 1 of the Connection Wizard lists all the events that the source component supports.
In this application, we want the button click event to call the animator’s startAnimation
method, so we need to connect the button’s action event to LogoAnimator’s start-
Animation method. Expand the action node, highlight actionPerformed and click
the Next button at the bottom of the Connection Wizard (Fig. 6.30). Step 2 (Fig. 6.31) lists
the methods or properties that can be set on the target component (LogoAnimator). Click
the Method Call radio button to show a list of LogoAnimator’s methods. Many of the
methods that appear in the list are inherited from LogoAnimator’s superclass—JPanel.
Select method startAnimation from the list and click the Finish button at the bottom
of the Connection Wizard (Fig. 6.31). Repeat the above procedure for the Stop Anima-
tion button, but select method stopAnimation in Step 2 of the Connection Wizard
Fig. 6.25
Fig. 6.25Fig. 6.25
Fig. 6.25 Component Palette Selection mode.
Fig. 6.26
Fig. 6.26Fig. 6.26
Fig. 6.26 Component Palette Connection mode.
Fig. 6.27
Fig. 6.27Fig. 6.27
Fig. 6.27 Select Connection mode.
334 JavaBeans Component Model Chapter 6
Fig. 6.28
Fig. 6.28Fig. 6.28
Fig. 6.28 Connecting JButton and LogoAnimator.
Fig. 6.29
Fig. 6.29Fig. 6.29
Fig. 6.29 Connection Wizard dialog.
Chapter 6 JavaBeans Component Model 335
Fig. 6.30

Fig. 6.30Fig. 6.30
Fig. 6.30 Select actionPerformed event.
Fig. 6.31
Fig. 6.31Fig. 6.31
Fig. 6.31 Selecting method startAnimation for the target component.
336 JavaBeans Component Model Chapter 6
To test that the connections between the buttons and the LogoAnimator work correctly,
execute the AnimationWindow application by right clicking AnimationWindow in
the Explorer window and selecting Execute from the menu (Fig. 6.32). Forte switches
to the Running tab and displays AnimationWindow (Fig. 6.33). AnimationWindow
contains the LogoAnimator and the two JButtons. Click the Stop Animation
button. The Deitel logo in LogoAnimator stops. Clicking the Start Animation button
starts the animation from the point it stopped.
Testing and Debugging Tip 6.1
A benefit of working in a bean-ready development environment is that the beans typically exe-
cute live in the development environment. This allows you to view your program immediately
in the design environment, rather than using the standard edit, compile and execute cycle.
6.1
Fig. 6.32
Fig. 6.32Fig. 6.32
Fig. 6.32 Select Execute from Explorer menu.
Fig. 6.33
Fig. 6.33Fig. 6.33
Fig. 6.33 AnimationWindow running in Forte.

×