1. Trang chủ
  2. » Công Nghệ Thông Tin

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

187 427 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 187
Dung lượng 1,94 MB

Nội dung

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 [...]... getAnimationDelay (lines 22 25 ) in Fig 6 .39 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 // Fig 6 .39 : LogoAnimator2 .java // LogoAnimator2 extends LogoAnimator to include // animationDelay property and implements ColorListener package com.deitel.advjhtp1.beans; // Java core packages import java. awt.*; import java. awt.event.*; // Java extension... the Java code for LogoAnimator (Fig 6 .34 ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 // Fig 6 .34 : LogoAnimator .java // LogoAnimator is a JavaBean containing an animated logo package com.deitel.advjhtp1.beans; // Java core packages import java. awt.*; import java. awt.event.*; import java. io.*; import java. net.*; // Java. .. Forte for Java Community Edition 2. 0 Fig 6 .2 Install New JavaBean menu item Fig 6 .3 Install JavaBean dialog Chapter 6 Chapter 6 Fig 6.4 JavaBeans Component Model 32 5 Select JavaBean and Palette Category dialogs Component Palette Fig 6.5 Beans tab in the Component Palette and tooltip for LogoAnimator JavaBean GUI JavaBeans must be added to a Java Container to be able to use the builder tool to edit the... 32 2 JavaBeans Component Model Chapter 6 Outline 6.1 Introduction 6 .2 Using Beans in Forte for Java Community Edition 6 .3 6.4 Preparing a Class to be a JavaBean Creating a JavaBean: Java Archive Files 6.5 JavaBean Properties 6.6 6.7 Bound Properties Indexed Properties and Custom Events 6.8 Customizing JavaBeans for Builder Tools 6.8.1 6.8 .2 6.9 PropertyEditors Customizers Internet... of a button in a reusable manner (e.g., Chapter 6 JavaBeans Component Model 32 3 javax.swing.JButton) A button is not specific to our example Rather, it is a component 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 buttons, typically have the same meaning in all programs.) However,... Component Palette Fig 6 .22 JButton icon in the Component Palette Fig 6 . 23 Adding a JButton to AnimationWindow Fig 6 .24 Editing text property of JButton Chapter 6 Chapter 6 JavaBeans Component Model 33 3 Next, we connect the Start Animation and Stop Animation buttons to the LogoAnimator so the user can start and stop the animation The button with the mouse pointer icon to the left of the Component Palette... the animation speed Lines 22 36 define LogoAnimator’s no-argument constructor Line 24 initializes array images with length totalImages Lines 29 33 load the PNG images into the array Line 35 invokes method startAnimation to start the LogoAnimator animation LogoAnimator overrides method paintComponent (lines 39 –46), inherited from class JPanel Method paintComponent draws LogoAnimator whenever it is called... 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 AnimationWindow selected in Explorer Fig 6 .20 Selecting FlowLayout in the Explorer menu 3 32 JavaBeans Component Model Fig 6 .21 Swing tab of the Component Palette Fig 6 .22 ... Finish button at the bottom of the Connection Wizard (Fig 6 .31 ) Repeat the above procedure for the Stop Animation button, but select method stopAnimation in Step 2 of the Connection Wizard Fig 6 .25 Component Palette Selection mode Fig 6 .26 Component Palette Connection mode Fig 6 .27 Select Connection mode 33 4 JavaBeans Component Model Fig 6 .28 Connecting JButton and LogoAnimator Fig 6 .29 Connection Wizard... 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 Select Execute from Explorer menu Fig 6 .33 AnimationWindow running in Forte Chapter 6 JavaBeans Component Model 33 7 6 .3 Preparing a Class to be a JavaBean In the previous section, we introduced the LogoAnimator JavaBean to demonstrate the basics of using JavaBeans . DrawingInternalFrame to desktopPane 23 0 desktopPane.add( frame ); 23 1 23 2 // make DrawingInternalFrame visible 23 3 frame.setVisible( true ); 23 4 23 5 // select new DrawingInternalFrame 23 6 try { 23 7 frame.setSelected(. events 22 3 frame.addInternalFrameListener( 22 4 new DrawingInternalFrameListener() ); 22 5 22 6 // make DrawingInternalFrame opaque 22 7 frame.setOpaque( true ); 22 8 22 9 // add DrawingInternalFrame to. screen 32 3 public void showSplashScreen() 32 4 { 32 5 // create ImageIcon for logo 32 6 Icon logoIcon = new ImageIcon( 32 7 getClass().getResource( "images/deitellogo.png" ) ); 32 8 32 9 //

Ngày đăng: 09/08/2014, 12:22

TỪ KHÓA LIÊN QUAN