Chapter 3 ModelViewController Outline 3 1 3 2






























































- Slides: 62
Chapter 3 – Model-View-Controller Outline 3. 1 3. 2 3. 3 3. 4 3. 5 3. 6 Introduction Model-View-Controller Architecture Observable Class and Observer Interface Jlist Jtable Jtree 3. 6. 1 Using Default. Tree. Model 3. 6. 2 Custom Tree. Model Implementation 2002 Prentice Hall. All rights reserved.
3. 1 Introduction • MVC – Model-view-controller architecture • Data components • Presentation components • Input-processing components • Delegate-model architecture • Observer design pattern 2002 Prentice Hall. All rights reserved.
3. 2 Model-View-Controller Architecture • Model – Application data • View – Graphical presentation components • Controller – Logic for processing user input Fig. 3. 1 2002 Prentice Hall. All rights reserved. Model-view-controller architecture.
3. 2 Model-View-Controller Architecture (Cont. ) • Delegate-model architecture – Variant of MVC – Combines the view and controller into a single object Fig. 3. 2 Delegate-model architecture in Java Swing components. 2002 Prentice Hall. All rights reserved.
3. 3 Observable Class and Observer Interface • Observer design pattern – Loose coupling • Java implementation of observer design pattern – Class java. util. Observable – Interface Observer • Example Fig. 3. 3 Account. Manager application MVC architecture. 2002 Prentice Hall. All rights reserved.
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 Outline // Account. java // Account is an Observable class that represents a bank // account in which funds may be deposited or withdrawn. package com. deitel. advjhtp 1. mvc. account; // Java core packages import java. util. Observable; Fig. 3. 4 Account Class Account extends class Observable class and acts as a model in the application. that represents a bank account. public class Account extends Observable { // Account balance private double balance; // readonly Account name private String name; Line 9 // Account constructor public Account( String account. Name, double opening. Deposit ) { Initialize the name and. Lines 18 -22 name = account. Name; balance properties. set. Balance( opening. Deposit ); Lines 25 -35 } // set Account balance and notify observers of change private void set. Balance( double account. Balance ) { Method set. Balance balance = account. Balance; Line 31 changes the Line 34 model by updating the account balance. // must call set. Changed before notify. Observers to Invokes method set. Changed of class // indicate model has changed Invokes method notify. Observers of flag. class set. Changed(); Observable to set the model’s changed Observable to notify all Account Obserbers of the change. // notify Observers that model has changed notify. Observers(); } 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 // get Account balance public double get. Balance() { return balance; } Outline Return the current Account balance. // withdraw funds from Account public void withdraw( double amount ) throws Illegal. Argument. Exception { if ( amount < 0 ) throw new Illegal. Argument. Exception ( "Cannot withdraw negative amount" ); // update Account balance set. Balance( get. Balance() - amount ); } // deposit funds in account public void deposit( double amount ) throws Illegal. Argument. Exception { if ( amount < 0 ) throw new Illegal. Argument. Exception ( "Cannot deposit negative amount" ); Method withdraw subtracts the given amount from the Account balance. Fig. 3. 4 Account Observable class that represents a bank account. Lines 38 -41 Method deposit adds the amount input to the Lines 44 -53 Account balance. Lines 56 -65 // update Account balance set. Balance( get. Balance() + amount ); } 2002 Prentice Hall. All rights reserved.
66 67 68 69 70 71 72 // get Account name ( readonly) public String get. Name() { return name; } Outline } Fig. 3. 4 Account Observable class that represents a bank account. 2002 Prentice Hall. All rights reserved.
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 // Abstract. Account. View. java // Abstract. Account. View is an abstract class that represents // a view of an Account. package com. deitel. advjhtp 1. mvc. account; Outline // Java core packages import java. util. *; import java. awt. *; // Java extension packages import javax. swing. JPanel; import javax. swing. border. *; public abstract class Abstract. Account. View extends JPanel implements Observer { // Account to observe private Account account; Fig. 3. 5 Abstract. Account. V iew abstract base class for observing Accounts. // Abstract. Account. View constructor Lines 21 -37 public Abstract. Account. View( Account observable. Account ) throws Null. Pointer. Exception Constructor sets the account member { Line 32 variable to the new Account. // do not allow null Accounts if ( observable. Account == null ) throw new Null. Pointer. Exception(); Invokes method add. Observer of class to register the newly created Abstract. Account. View instance as an account updates Observer of the new Account. // update account data member to new Account Observable account = observable. Account; // register as an Observer to receive account. add. Observer( this ); 2002 Prentice Hall. All rights reserved.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 Outline // set display properties set. Background( Color. white ); set. Border( new Matte. Border( 1, 1, Color. black ) ); } // get Account for which this view is an Observer public Account get. Account() Method update. Display { return account; abstract, requiring each } } is marked Abstract. Account. View subclass to // update display with Account balance provide an appropriate implementation for Fig. 3. 5 protected abstract void update. Display(); displaying the Account information. Abstract. Account. V // receive updates from Observable Account iew abstract public void update( Observable observable, Object object ) base class for { Method update invokes method update. Display observing update. Display(); } each time an Account notifies the Accounts. Abstract. Account. View of a change. Line 46 Lines 49 -52 2002 Prentice Hall. All rights reserved.
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 // Account. Text. View. java // Account. Text. View is an Abstract. Account. View subclass // that displays an Account balance in a JText. Field. package com. deitel. advjhtp 1. mvc. account; Outline // Java core packages import java. util. *; import java. text. Number. Format; // Java extension packages import javax. swing. *; Fig. 3. 6 Account. Text. View public class Account. Text. View extends Abstract. Account. View { for displaying Extends Abstract. Account. View // JText. Field for displaying Account balance observed Account private JText. Field balance. Text. Field = new JText. Field( 10 ); a text-basedfield viewtoof information in Createtoaprovide Number. Format format Account data. as U. S. JText. Field. the Account balance dollars. // Number. Format for US dollars private Number. Format money. Format = Number. Format. get. Currency. Instance( Locale. US ); // Account. Text. View constructor public Account. Text. View( Account account ) { super( account ); // make balance. Text. Field readonly balance. Text. Field. set. Editable( false ); Line 13 Lines 19 -20 Makes the balance. Text. Field 28 uneditable to prevent. Line users from modifying the balance directly. // lay out components add( new JLabel( "Balance: " ) ); add( balance. Text. Field ); update. Display(); } 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 Method update. Display implements Outline abstract method update. Display of class Abstract. Account. View. // update display with Account balance public void update. Display() { // set text in balance. Text. Field to formatted balance. Text. Field. set. Text( money. Format. format( get. Account(). get. Balance() ) ); Set the } } balance. Text. Field’s text to the formatted Account balance. Fig. 3. 6 Account. Text. View for displaying observed Account information in JText. Field. Lines 38 -43 Lines 41 -42 2002 Prentice Hall. All rights reserved.
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 // Account. Bar. Graph. View. java // Account. Bar. Graph. View is an Abstract. Account. View subclass // that displays an Account balance as a bar graph. package com. deitel. advjhtp 1. mvc. account; Outline // Java core packages import java. awt. *; // Java extension packages import javax. swing. *; Fig. 3. 7 Account. Bar. Graph. V Extends Abstract. Account. View iewoffor to provide a bar-graph view rendering Account data. observed Account information as a bar graph. public class Account. Bar. Graph. View extends Abstract. Account. View { // Account. Bar. Graph. View constructor public Account. Bar. Graph. View( Account account ) { super( account ); } // draw Account balance as a bar graph public void paint. Component( Graphics g ) { // ensure proper painting sequence super. paint. Component( g ); // get Account balance double balance = get. Account(). get. Balance(); Line 12 Method paint. Component draws a bar graph for the Lines 21 -57 current Account balance. // calculate integer height for bar graph (graph // is 200 pixels wide and represents Account balances // from -$5, 000. 00 to +$5, 000. 00) int bar. Length = ( int ) ( ( balance / 10000. 0 ) * 200 ); 2002 Prentice Hall. All rights reserved.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 // if balance is positive, draw graph in black if ( balance >= 0. 0 ) { g. set. Color( Color. black ); g. fill. Rect( 105, 15, bar. Length, 20 ); } Outline Draw the bar graph in black for positive Account balance and in red for negative Account balance. // if balance is negative, draw graph in red else { g. set. Color( Color. red ); g. fill. Rect( 105 + bar. Length, 15, -bar. Length, 20 ); } // draw vertical and horizontal axes g. set. Color( Color. black ); g. draw. Line( 5, 205, 25 ); g. draw. Line( 105, 5, 105, 45 ); // draw graph labels g. set. Font( new Font( "Sans. Serif", Font. PLAIN, 10 ) ); g. draw. String( "-$5, 000", 5, 10 ); g. draw. String( "$0", 110, 10 ); g. draw. String( "+$5, 000", 166, 10 ); } // end method paint. Component Fig. 3. 7 Account. Bar. Graph. V iew for rendering observed Account information as a bar graph. Lines 35 -44 Lines 60 -63 // repaint graph when display is updated Line 68 public void update. Display() Method update. Display { repaint(); invokes method repaint to } Returns a new Dimension object that specifies update the bar graph’s display. Account. Bar. Graph. View's preferred size the Account. Bar. Graph. View’s preferred size Dimension get. Preferred. Size() as 210 pixels wide by 50 pixels high. // get public { return new Dimension( 210, 50 ); 2002 Prentice Hall. All rights reserved.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 } // get Account. Bar. Graph. View's minimum size public Dimension get. Minimum. Size() { return get. Preferred. Size(); } // get Account. Bar. Graph. View's maximum size public Dimension get. Maximum. Size() { return get. Preferred. Size(); } } Outline Override methods get. Minimum. Size and get. Maximum. Size to return the Account. Bar. Graph. View’s preferred size. Fig. 3. 7 Account. Bar. Graph. V iew for rendering observed Account information as a bar graph. Lines 72 -81 2002 Prentice Hall. All rights reserved.
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 // Asset. Pie. Chart. View. java // Asset. Pie. Chart. View is an Abstract. Account. View subclass that // displays multiple asset Account balances as a pie chart. package com. deitel. advjhtp 1. mvc. account; Outline // Java core packages import java. awt. *; import java. util. List; // Java extension packages import javax. swing. *; import javax. swing. border. *; Fig. 3. 8 Asset. Pie. Chart. Vie w for rendering multiple observed asset Accounts as a pie chart. public class Asset. Pie. Chart. View extends JPanel implements Observer { // Set of observed Accounts private List accounts = new Array. List(); // Map of Colors for drawing pie chart wedges private Map colors = new Hash. Map(); // add Account to pie chart view public void add. Account( Account account ) { // do not add null Accounts if ( account == null ) throw new Null. Pointer. Exception(); // add Account to accounts Vector accounts. add( account ); Lines 25 -42 Method add. Account adds an Account to the List of Accounts Line 35 shown in the pie chart. Invokes method get. Random. Color and adds the random Color to the colors Map. // add Color to Hashtable for drawing Account's wedge colors. put( account, get. Random. Color() ); 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 Invokes method add. Observer // register as Observer to receive Account updates Account to register the account. add. Observer( this ); Outline of class Asset. Pie. Chart. View for Account updates. to display the pie chart with the } new Account’s information. Fig. 3. 8 // remove Account from pie chart view Asset. Pie. Chart. Vie public void remove. Account( Account account ) w for rendering Invokes method delete. Observer { Method remove. Account removes multiple // stop receiving updates from given Account of class Account tochart. unregister an Account from the pie account. delete. Observer( this ); observed asset the Asset. Pie. Chart. View as an Accounts as a Observer of the Account. // remove Account from accounts Vector pie chart. accounts. remove( account ); Invokes method repaint // update display with new Account information repaint(); // remove Account's Color from Hashtable colors. remove( account ); Line 38 // update display to remove Account information repaint(); Line 41 } // draw Account balances in a pie chart public void paint. Component( Graphics g ) { // ensure proper painting sequence super. paint. Component( g ); Lines 45 -58 Method paint. Component invokes method draw. Pie. Chart 48 pie and draw. Legend to. Line draw the chart and chart legend respectively. Lines 61 -71 // draw pie chart draw. Pie. Chart( g ); 2002 Prentice Hall. All rights reserved.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 Outline // draw legend to describe pie chart wedges draw. Legend( g ); } // draw pie chart on given Graphics context private void draw. Pie. Chart( Graphics g ) { // get combined Account balance double total. Balance = get. Total. Balance(); Method draw. Pie. Chart draws a pie-chart wedge for each Account. Fig. 3. 8 Asset. Pie. Chart. Vie w for rendering multiple observed asset Iterator account. Iterator = accounts. iterator(); Account account = null; Accounts as a pie chart. The while loop calculates the // draw pie wedge for each Account while ( account. Iterator. has. Next() ) { percentage of the total balance held in each Account and Lines draw the 74 -112 wedges. // create temporary variables for pie chart calculations double percentage = 0. 0; int start. Angle = 0; int arc. Angle = 0; // get next Account from Iterator account = ( Account ) account. Iterator. next(); // draw wedges only for included Accounts if ( !include. Account. In. Chart( account ) ) Invokes continue; Lines 88 -111 method include. Account. In. Chart Line 94 to determine if the pie chart should include the current held in. Account // get percentage of total balance percentage = account. get. Balance() / total. Balance; // calculate arc angle for percentage arc. Angle = ( int ) Math. round( percentage * 360 ); 2002 Prentice Hall. All rights reserved.
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 // set drawing Color for Account pie wedge g. set. Color( ( Color ) colors. get( account ) ); // draw Account pie wedge g. fill. Arc( 5, 5, 100, start. Angle, arc. Angle ); Invokes method fill. Arc Outline of class Graphics to draw the Account’s pie wedge. // calculate start. Angle for next pie wedge start. Angle += arc. Angle; Fig. 3. 8 Asset. Pie. Chart. Vie w for rendering // draw pie chart legend on given Graphics context Method draw. Legend draws a multiple private void draw. Legend( Graphics g ) legend to show which color observed asset { represents each Account. Iterator account. Iterator = accounts. iterator(); Accounts as a Account account = null; pie chart. } } // end method draw. Pie. Chart // create Font for Account name Font font = new Font( "Sans. Serif", Font. BOLD, 12 ); g. set. Font( font ); // get Font. Metrics for calculating offsets and // positioning descriptions Font. Metrics metrics = get. Font. Metrics( font ); int ascent = metrics. get. Max. Ascent(); int offset. Y = ascent + 2; // draw description for each Account for ( int i = 1; account. Iterator. has. Next(); i++ ) { // get next Account from Iterator account = ( Account ) account. Iterator. next(); Line 107 Use a Font. Metrics object to calculate the Lines 115 -145 heights of characters in the current Font. Lines 121 -128 Lines 131 -144 The for loop draw the legend item for each Account. 2002 Prentice Hall. All rights reserved.
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 // draw Account color swatch at next offset g. set. Color( ( Color ) colors. get( account ) ); g. fill. Rect( 125, offset. Y * i, ascent ); Outline // draw Account name next to color swatch g. set. Color( Color. black ); g. draw. String( account. get. Name(), 140, offset. Y * i + ascent ); } } // end method draw. Legend Method get. Total. Balance Fig. 3. 8 // get combined balance of all observed Accounts private double get. Total. Balance() calculates the total balance for Asset. Pie. Chart. Vie { all included Accounts. w for rendering double sum = 0. 0; Iterator account. Iterator = accounts. iterator(); Account account = null; // calculate total balance while ( account. Iterator. has. Next() ) { account = ( Account ) account. Iterator. next(); // add only included Accounts to sum if ( include. Account. In. Chart( account ) ) sum += account. get. Balance(); } multiple observed asset Accounts as a pie chart. Lines 148 -164 Adds the Account’s balance to Line 161 variable sum if the calculation should include the Account. return sum; } 2002 Prentice Hall. All rights reserved.
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 Outline // return true if given Account should be included in // pie chart protected boolean include. Account. In. Chart( Account account ) { Method include. Account. In. Chart returns // include only Asset accounts (Accounts with positive a boolean indicating whether the Account // balances) return account. get. Balance() > 0. 0; should be included in the pie chart. } // get a random Color for drawing pie wedges. Asset. Pie. Chart. View uses Fig. 3. 8 private Color get. Random. Color() method get. Random. Color to Asset. Pie. Chart. Vie { generate a different Color for // calculate random red, green and blue values w for rendering each Account in the pie chart. int red = ( int ) ( Math. random() * 256 ); multiple int green = ( int ) ( Math. random() * 256 ); observed asset int blue = ( int ) ( Math. random() * 256 ); // return newly created Color return new Color( red, green, blue ); Accounts as a pie chart. } Lines 169 -174 // receive updates from Observable Account public void update( Observable observable, Object object ) Lines { Method update invokes method repaint(); repaint to update the pie-chart display. } 177 -186 Lines 189 -192 // get Account. Bar. Graph. View's preferred size public Dimension get. Preferred. Size() { return new Dimension( 210, 110 ); } 2002 Prentice Hall. All rights reserved.
200 201 202 203 204 205 206 207 208 209 210 211 // get Account. Bar. Graph. View's preferred size public Dimension get. Minimum. Size() { return get. Preferred. Size(); } Outline // get Account. Bar. Graph. View's preferred size public Dimension get. Maximum. Size() { return get. Preferred. Size(); } } Fig. 3. 8 Asset. Pie. Chart. Vie w for rendering multiple observed asset Accounts as a pie chart. 2002 Prentice Hall. All rights reserved.
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 // Account. Controller. java // Account. Controller is a controller for Accounts. It provides // a JText. Field for inputting a deposit or withdrawal amount // and JButtons for depositing or withdrawing funds. package com. deitel. advjhtp 1. mvc. account; Outline // Java core packages import java. awt. *; import java. awt. event. *; // Java extension packages import javax. swing. *; public class Account. Controller extends JPanel { // Account to control private Account account; // JText. Field for deposit or withdrawal amount private JText. Field amount. Text. Field ; // Account. Controller constructor public Account. Controller( Account controlled. Account ) { super(); Fig. 3. 9 Account. Controller implements Accountcontrolle the controller in the r for obtaining MVC architecture. user input to modify Account information. Line 14 Line 31 // account to control account = controlled. Account; // create JText. Field for entering amount. Text. Field = new JText. Field( 10 ); Creates a JText. Field into which users can enter an amount to withdraw from, or deposit in, the controlled Account. 2002 Prentice Hall. All rights reserved.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 Outline // create JButton for deposits JButton deposit. Button = new JButton( "Deposit" ); deposit. Button. add. Action. Listener( new Action. Listener() { Create a JButton for depositing the given amount into the Account. public void action. Performed( Action. Event event ) { try { // deposit amount entered in amount. Text. Field account. deposit( Double. parse. Double( amount. Text. Field. get. Text() ) ); } catch ( Number. Format. Exception exception ) { JOption. Pane. show. Message. Dialog ( Account. Controller. this, "Please enter a valid amount" , "Error", JOption. Pane. ERROR_MESSAGE ); } } // end method action. Performed } Fig. 3. 9 Accountcontrolle r for obtaining user input to modify Account information. Lines 34 -56 Lines 59 -81 ); // create JButton for withdrawals JButton withdraw. Button = new JButton( "Withdraw" ); withdraw. Button. add. Action. Listener( new Action. Listener() { Create a JButton for withdrawing the given amount from the Account. public void action. Performed( Action. Event event ) { 2002 Prentice Hall. All rights reserved.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 try { Outline // withdraw amount entered in amount. Text. Field account. withdraw( Double. parse. Double( amount. Text. Field. get. Text() ) ); } catch ( Number. Format. Exception exception ) { JOption. Pane. show. Message. Dialog ( Account. Controller. this, "Please enter a valid amount" , "Error", JOption. Pane. ERROR_MESSAGE ); } } // end method action. Performed } ); // lay out controller components set. Layout( new Flow. Layout() ); add( new JLabel( "Amount: " ) ); add( amount. Text. Field ); add( deposit. Button ); add( withdraw. Button ); Fig. 3. 9 Accountcontrolle r for obtaining user input to modify Account information. } } 2002 Prentice Hall. All rights reserved.
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 // Account. Manager. java // Account. Manager is an application that uses the MVC design // pattern to manage bank Account information. package com. deitel. advjhtp 1. mvc. account; Outline // Java core packages import java. awt. *; import java. awt. event. *; Fig. 3. 10 Account. Manager // Java extension packages import javax. swing. *; application for import javax. swing. border. *; displaying and modifying public class Account. Manager extends JFrame { Account // Account. Manager no-argument constructor information public Account. Manager() using the model{ super( "Account Manager" ); view-controller architecture. Creates a new Account // create account 1 with initial balance Account account 1 = new Account( "Account 1", 1000. 00 ); with the name Account Lines 22 and 28 Invokes method 1 and a $1, 000. 00 // create GUI for account 1 get. Account. Panel of balance, and Account JPanel account 1 Panel = create. Account. Panel( account 1 ); class 2 Account. Manager to Lines 25 and 31 with a $3, 000. 00 // create account 2 with initial balance create a JPanel containing balance. Account account 2 = new Account( "Account 2", 3000. 00 ); Lines 34 -35 view and controller components for account 1 // create GUI for account 2 Create an Asset. Pie. Chart. View JPanel account 2 Panel = create. Account. Panel( account 2 ); and account 2. for displaying account 1 and account 2 // create Account. Pie. Chart. View to show Account pie chart information in a pie chart. Asset. Pie. Chart. View pie. Chart. View = new Asset. Pie. Chart. View(); 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 Outline Invoke method add. Account of class Asset. Pie. Chart. View to add account 1 and account 2 to the pie chart. Fig. 3. 10 // create JPanel for Account. Pie. Chart. View JPanel pie. Chart. Panel = new JPanel(); Account. Manager Create a JPanelapplication with a for pie. Chart. Panel. set. Border( Titled. Border for the displaying and new Titled. Border( "Assets" ) ); Asset. Pie. Chart. View. modifying pie. Chart. Panel. add( pie. Chart. View ); Account information // lay out account 1, account 2 and pie chart components Container content. Pane = get. Content. Pane(); using the modelcontent. Pane. set. Layout( new Grid. Layout( 3, 1 ) ); view-controller Lay out the JPanels for each account content. Pane. add( account 1 Panel ); architecture. and Asset. Pie. Chart. View. content. Pane. add( account 2 Panel ); // add both Accounts to Account. Pie. Chart. View pie. Chart. View. add. Account( account 1 ); pie. Chart. View. add. Account( account 2 ); content. Pane. add( pie. Chart. Panel ); set. Size( 425, 450 ); } // end Account. Manager constructor Lines 38 -39 Lines 42 -47 // create GUI components for given Account Lines 50 -54 private JPanel create. Account. Panel ( Account account )Method create. Account. Panel { creates a JPanel containing an // create JPanel for Account GUI Account. Controller, Lines Create a JPanel with a 61 -89 JPanel account. Panel = new JPanel(); // set JPanel's border to show Account name account. Panel. set. Border( new Titled. Border( account. get. Name() ) ); Account. Text. View Titled. Border toand contain the Account. Bar. Graph. View for the Lines 64 -68 Account’s GUI components. given Account. 2002 Prentice Hall. All rights reserved.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 // create Account. Text. View for Account. Text. View account. Text. View = new Account. Text. View( account ); // create Account. Bar. Graph. View for Account. Bar. Graph. View account. Bar. Graph. View = new Account. Bar. Graph. View( account ); // create Account. Controller for Account. Controller account. Controller = new Account. Controller( account ); // lay out Account's components account. Panel. add( account. Controller ); account. Panel. add( account. Text. View ); account. Panel. add( account. Bar. Graph. View ); return account. Panel; } // end method get. Account. Panel Outline Create an Account. Text. View for the Account. Create an Account. Bar. Graph. View for the Account. Fig. 3. 10 Account. Manager application for Create an Account. Controller displaying and for the Account. modifying Lay out the Account. Textview, Account and Account. Bar. Graph. View information Account. Controller using the modelcomponents on account. Panel. view-controller architecture. // execute application public static void main( String args[] ) { Account. Manager manager = new Account. Manager(); manager. set. Default. Close. Operation ( EXIT_ON_CLOSE ); manager. set. Visible( true ); } } Lines 71 -72 Lines 75 -76 Lines 79 -80 Lines 83 -85 2002 Prentice Hall. All rights reserved.
Outline Fig. 3. 10 Account. Manager application for displaying and modifying Account information using the modelview-controller architecture. Program output 2002 Prentice Hall. All rights reserved.
3. 4 JList • JList – Implements the delegate-model architecture – Delegates for List. Models • List. Model – Define methods – Register/unregister List. Data. Listener Fig. 3. 11 JList and List. Model delegate-model architecture. 2002 Prentice Hall. All rights reserved.
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 // Philosophers. JList. java // MVC architecture using JList with a Default. List. Model package com. deitel. advjhtp 1. mvc. list; Outline // Java core packages import java. awt. *; import java. awt. event. *; // Java extension packages import javax. swing. *; public class Philosophers. JList extends JFrame { private Default. List. Model philosophers; private JList list; // Philosophers. JList constructor public Philosophers. JList() { super( "Favorite Philosophers" ); Fig. 3. 12 Philosophers. JLis t application demonstrating Jlist and Default. List. Model. Line 23 // create a Default. List. Model to store philosophers Creates a new Default. List. Model philosophers = new Default. List. Model(); Lines 24 -31 which provides a basic List. Model philosophers. add. Element( "Socrates" ); implementation. philosophers. add. Element( "Plato" ); Line 34 philosophers. add. Element( "Aristotle" ); Add several philosophers to philosophers. add. Element( "St. Thomas Aquinas" ); the Default. List. Model. philosophers. add. Element( "Soren Kierkegaard" ); philosophers. add. Element( "Immanuel Kant" ); philosophers. add. Element( "Friedrich Nietzsche" ); philosophers. add. Element( "Hannah Arendt" ); // create a JList for philosophers list = new JList( philosophers ); Creates a new JList and passes the Default. List. Model philosophers Default. List. Model to the JList constructor. 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 Outline // allow user to select only one philosopher a JList’s time Setatthe selection mode to allow the list. set. Selection. Mode( List. Selection. Model. SINGLE_SELECTION ); user to select only one philosopher at a time. // create JButton for adding philosophers JButton add. Button = new JButton( "Add Philosopher" ); add. Button. add. Action. Listener( Create a JButton for adding new Action. Listener() { philosophers to the Default. List. Model. Fig. 3. 12 Philosophers. JLis t application demonstrating and Invokes method. Jlist add. Element of Default. List. Model. class Default. List. Model to add the new philosopher to the list. Lines 37 -38 public void action. Performed( Action. Event event ) { // prompt user for new philosopher's name String name = JOption. Pane. show. Input. Dialog( Philosophers. JList. this, "Enter Name" ); // add new philosopher to model philosophers. add. Element( name ); } } ); // create JButton for removing selected philosopher JButton remove. Button = new JButton( "Remove Selected Philosopher" ); remove. Button. add. Action. Listener( new Action. Listener() { Line 52 Create a JButton for deleting a philosophers from the Default. List. Model. Lines 58 -71 public void action. Performed( Action. Event event ) { // remove selected philosopher from model philosophers. remove. Element( list. get. Selected. Value() ); } } Lines 41 -55 2002 Prentice Hall. All rights reserved.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 Outline ); // lay out GUI components JPanel input. Panel = new JPanel(); input. Panel. add( add. Button ); input. Panel. add( remove. Button ); Lay out the GUI components and set JFrame properties for the application window. Container container = get. Content. Pane(); container. add( list, Border. Layout. CENTER ); container. add( input. Panel, Border. Layout. NORTH ); set. Default. Close. Operation ( EXIT_ON_CLOSE ); set. Size( 400, 300 ); set. Visible( true ); } // end Philosophers. JList constructor // execute application public static void main( String args[] ) { new Philosophers. JList(); } } Fig. 3. 12 Philosophers. JLis t application demonstrating Jlist and Default. List. Model. Lines 74 -84 2002 Prentice Hall. All rights reserved.
Outline Fig. 3. 12 Philosophers. JLis t application demonstrating Jlist and Default. List. Model. Program output 2002 Prentice Hall. All rights reserved.
3. 5 JTable • JTable – Implements the delegate-model architecture – Delegates for Table. Models • Table. Model – Declare methods • Retrieving and modifying data Fig. 3. 14 JTable and Table. Model delegate-model architecture. 2002 Prentice Hall. All rights reserved.
3. 5 Jtable (Cont. ) Fig. 3. 13 (Part 1 of 2) Table. Model interface methods and descriptions. 2002 Prentice Hall. All rights reserved.
3. 5 JTable (Cont. ) Fig. 3. 13 (Part 2 of 2) Table. Model interface methods and descriptions. 2002 Prentice Hall. All rights reserved.
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 // Philosophers. JTable. java // MVC architecture using JTable with a Default. Table. Model package com. deitel. advjhtp 1. mvc. table; Outline // Java core packages import java. awt. *; import java. awt. event. *; // Java extension packages import javax. swing. *; import javax. swing. table. *; Fig. 3. 15 Philosophers. JTab le application demonstrating JTable and Default. Table. Mode l. public class Philosophers. JTable extends JFrame { private Default. Table. Model philosophers; private JTable table; // Philosophers. JTable constructor public Philosophers. JTable() { super( "Favorite Philosophers" ); Line 24 // create a Default. Table. Model to store philosophers Creates philosophers = new Default. Table. Model(); the philosophers Lines 27 -29 Default. Table. Model. // add Columns to Default. Table. Model philosophers. add. Column( "First Name" ); philosophers. add. Column( "Last Name" ); philosophers. add. Column( "Years" ); Add columns to the Default. Table. Model Lines 32 -53 for the philosophers’ first names, last names and years in which they lived. // add philosopher names and dates to Default. Table. Model String[] socrates = { "Socrates", "469 -399 B. C. " }; philosophers. add. Row( socrates ); Create rows for seven philosophers. 2002 Prentice Hall. All rights reserved.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 String[] plato = { "Plato", "428 -347 B. C. " }; philosophers. add. Row( plato ); Outline String[] aquinas = { "Thomas", "Aquinas", "1225 -1274" }; philosophers. add. Row( aquinas ); String[] kierkegaard = { "Soren", "Kierkegaard", "1813 -1855" }; philosophers. add. Row( kierkegaard ); String[] kant = { "Immanuel", "Kant", "1724 -1804" }; philosophers. add. Row( kant ); String[] nietzsche = { "Friedrich", "Nietzsche", "1844 -1900" }; philosophers. add. Row( nietzsche ); String[] arendt = { "Hannah", "Arendt", "1906 -1975" }; philosophers. add. Row( arendt ); Fig. Create rows 3. 15 for Philosophers. JTab seven philosophers. le application demonstrating JTable and Default. Table. Mode l. // create a JTable for philosophers Default. Table. Model Creates the table = new JTable( philosophers ); JTable that will act 32 -53 Lines as a delegate for the philosophers Default. Table. Model. Line 56 // create JButton for adding philosophers JButton add. Button = new JButton( "Add Philosopher" ); add. Button. add. Action. Listener( Create a JButton new Action. Listener() { and Action. Listener Lines 59 -72 for adding a new philosopher to the Action. Event event ) Default. Table. Model. public void action. Performed( { // create empty array for new philosopher row String[] philosopher = { "", "" }; // add empty philosopher row to model philosophers. add. Row( philosopher ); 2002 Prentice Hall. All rights reserved.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 Outline } ); // create JButton for removing selected philosopher JButton remove. Button = new JButton( "Remove Selected Philosopher" ); remove. Button. add. Action. Listener( new Action. Listener() { Create a JButton and Action. Listener for removing a philosopher from the Default. Table. Model. public void action. Performed( Action. Event event ) { // remove selected philosopher from model philosophers. remove. Row( table. get. Selected. Row() ); } } ); // lay out GUI components JPanel input. Panel = new JPanel(); input. Panel. add( add. Button ); input. Panel. add( remove. Button ); Container container = get. Content. Pane(); Add the JTable container. add( new JScroll. Pane( table ), JScroll. Pane. Border. Layout. CENTER ); container. add( input. Panel, Border. Layout. NORTH ); Fig. 3. 15 Philosophers. JTab le application demonstrating JTable and Default. Table. Mode l. Lines 75 -88 to a. Lines 96 -97 set. Default. Close. Operation ( EXIT_ON_CLOSE ); set. Size( 400, 300 ); set. Visible( true ); } // end Philosophers. JTable constructor 2002 Prentice Hall. All rights reserved.
105 106 107 108 109 110 111 // execute application public static void main( String args[] ) { new Philosophers. JTable(); } Outline } Fig. 3. 15 Philosophers. JTab le application demonstrating JTable and Default. Table. Mode l. Program output 2002 Prentice Hall. All rights reserved.
3. 6 JTree • JTree – Implements the delegate-model architecture – Delegates for Tree. Models • Tree. Model – Hierarchical data • • • Parents Children Siblings Ancestors Descendents 2002 Prentice Hall. All rights reserved.
3. 6 Jtree (Cont. ) Fig. 3. 16 JTree showing a hierarchy of philosophers. 2002 Prentice Hall. All rights reserved.
3. 6. 1 Using Default. Tree. Model • Interface Tree. Model – Declares methods for representing tree structure • Class Default. Tree. Model – Default Tree. Model implementation • Tree. Node • Mutable. Tree. Node • Default. Mutable. Tree. Node 2002 Prentice Hall. All rights reserved.
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 // Philosophers. JTree. java // MVC architecture using JTree with a Default. Tree. Model package com. deitel. advjhtp 1. mvc. tree; Outline // Java core packages import java. awt. *; import java. awt. event. *; import java. util. *; // Java extension packages import javax. swing. *; import javax. swing. tree. *; public class Philosophers. JTree extends JFrame { private JTree tree; private Default. Tree. Model philosophers; private Default. Mutable. Tree. Node root. Node ; // Philosophers. JTree constructor public Philosophers. JTree() { super( "Favorite Philosophers" ); Fig. 3. 17 Philosophers. JTre e application demonstrating Jtree and Default. Tree. Model. Lines 26 -27 Invoke method Line 30 create. Philosopher. Tree to Creates a Default. Tree. Model and // get tree of philosopher Default. Mutable. Tree. Nodes get the root, passes the philosophers. Node Line 33 Default. Mutable. Tree. Node philosophers. Node = Default. Mutable. Tree. Node, create. Philosopher. Tree (); Default. Mutable. Tree. Node to the Creates awhich JTree and passes contains all the philosopher Default. Tree. Model constructor. // create philosophers Default. Tree. Model philosophers nodes. philosophers = new Default. Tree. Model( philosophers. Node ); to the JTree constructor. // create JTree for philosophers Default. Tree. Model tree = new JTree( philosophers ); 2002 Prentice Hall. All rights reserved.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 // create JButton for adding philosophers JButton add. Button = new JButton( "Add" ); add. Button. add. Action. Listener( new Action. Listener() { Create a JButton and an Outline Action. Listener for adding a philosopher to the philosophers Default. Tree. Model. public void action. Performed( Action. Event event ) { add. Element (); } } ); // create JButton for removing selected JButton remove. Button = new JButton( "Remove" ); remove. Button. add. Action. Listener( new Action. Listener() { Fig. 3. 17 philosopher Philosophers. JTre Create a JButton and e an application Action. Listener for removing a demonstrating Jtree and philosopher from the philosophers Default. Tree. Model. public void action. Performed( Action. Event event ) { remove. Element (); } } ); Lines 36 -45 Lines 48 -59 // lay out GUI components JPanel input. Panel = new JPanel(); input. Panel. add( add. Button ); input. Panel. add( remove. Button ); Container container = get. Content. Pane(); container. add( new JScroll. Pane( tree ), Border. Layout. CENTER ); 2002 Prentice Hall. All rights reserved.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 container. add( input. Panel, Border. Layout. NORTH ); Outline set. Default. Close. Operation ( EXIT_ON_CLOSE ); set. Size( 400, 300 ); set. Visible( true ); } // end Philosophers. JTree constructor Method add. Element gets the currently selected node in the JTree Fig. 3. 17 and inserts the new philosopher. Philosophers. JTre node as a child of the currently selectedenode. application // add new philosopher to selected era private void add. Element() { // get selected era Default. Mutable. Tree. Node parent = get. Selected. Node(); // ensure user selected era first if ( parent == null ) { JOption. Pane. show. Message. Dialog( Philosophers. JTree. this, "Select an era. ", "Error", JOption. Pane. ERROR_MESSAGE ); return; } // prompt user for philosopher's name String name = JOption. Pane. show. Input. Dialog( Philosophers. JTree. this, "Enter Name: " ); // add new philosopher to selected era philosophers. insert. Node. Into( new Default. Mutable. Tree. Node( name ), parent. get. Child. Count() ); } // end method add. Element demonstrating Jtree and Default. Tree. Model. Lines 80 -103 Lines 99 -101 Line 101 Invoke method insert. Node. Into of Invokes method get. Child. Count of class Default. Tree. Model to insert class Default. Mutable. Tree. Node the new philosopher in the model. to get the total number of children in node parent. 2002 Prentice Hall. All rights reserved.
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 Outline // remove currently selected philosopher Invokes method get. Selected. Node to get private void remove. Element() the currently selected node in the JTree. { // get selected node Default. Mutable. Tree. Node selected. Node = get. Selected. Node(); Invokes method Fig. 3. 17 // remove selected. Node from model remove. Node. From. Parent of class Philosophers. JTre if ( selected. Node != null ) Default. Tree. Model toe remove application philosophers. remove. Node. From. Parent( selected. Node ); selected. Node from the model. demonstrating } Jtree and // get currently selected node Default. Tree. Model. private Default. Mutable. Tree. Node get. Selected. Node ()Invokes method { get. Last. Selected. Path. Component of // get selected Default. Mutable. Tree. Node Lines 106 -114 class JTree to get a reference to the return ( Default. Mutable. Tree. Node ) tree. get. Last. Selected. Path. Component (); currently selected node. Line 113 } // get tree of philosopher Default. Mutable. Tree. Nodes Lines 117 -122 private Default. Mutable. Tree. Node create. Philosopher. Tree () { Method // create root. Node Createcreate. Philosopher. Tree a Default. Mutable. Tree. Node Lines 125 -192 Default. Mutable. Tree. Node root. Node = creates Default. Mutable. Tree. Nodes for the tree’s root. new Default. Mutable. Tree. Node( "Philosophers" ); // Ancient philosophers Default. Mutable. Tree. Node ancient = new Default. Mutable. Tree. Node( "Ancient" ); root. Node. add( ancient ); for several philosophers and for 128 -129 the eras in Create a Create Lines which the. Default. Mutable. Tree. Nodes philosophers lived. Default. Mutable. Tree. Node for the ancient for three eraancient of Lines philosophy philosophers and 132 -134 and add nodeeach ancient as a child as aofchild ancient of root. Node. Default. Mutable. Tree. Node. Lines 136 -138 ancient. add( new Default. Mutable. Tree. Node( "Socrates" ) ); ancient. add( new Default. Mutable. Tree. Node( "Plato" ) ); ancient. add( new Default. Mutable. Tree. Node( "Aristotle" ) ); 2002 Prentice Hall. All rights reserved.
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 // Medieval philosophers Default. Mutable. Tree. Node medieval = new Default. Mutable. Tree. Node( "Medieval" ); root. Node. add( medieval ); Outline medieval. add( new Default. Mutable. Tree. Node( "St. Thomas Aquinas" ) ); // Renaissance philosophers Default. Mutable. Tree. Node renaissance = new Default. Mutable. Tree. Node( "Renaissance" ); root. Node. add( renaissance ); renaissance. add( new Default. Mutable. Tree. Node( "Thomas More" ) ); // Early Modern philosophers Default. Mutable. Tree. Node early. Modern = new Default. Mutable. Tree. Node( "Early Modern" ); root. Node. add( early. Modern ); early. Modern. add( new Default. Mutable. Tree. Node( "John Locke" ) ); Create several additional Fig. 3. 17 Default. Mutable. Tree. Nodes for other eras. Philosophers. JTre in the history of e application philosophy and for philosophers in those eras. demonstrating Jtree and Default. Tree. Model. Lines 141 -189 // Enlightenment Philosophers Default. Mutable. Tree. Node enlightenment = new Default. Mutable. Tree. Node( "Enlightenment" ); root. Node. add( enlightenment ); enlightenment. add( new Default. Mutable. Tree. Node( "Immanuel Kant" ) ); 2002 Prentice Hall. All rights reserved.
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 // 19 th Century Philosophers Default. Mutable. Tree. Node nineteenth = new Default. Mutable. Tree. Node( "19 th Century" ); root. Node. add( nineteenth ); Outline nineteenth. add( new Default. Mutable. Tree. Node( "Soren Kierkegaard" ) ); nineteenth. add( new Default. Mutable. Tree. Node( "Friedrich Nietzsche" ) ); // 20 th Century Philosophers Default. Mutable. Tree. Node twentieth = new Default. Mutable. Tree. Node( "20 th Century" ); root. Node. add( twentieth ); twentieth. add( new Default. Mutable. Tree. Node( "Hannah Arendt" ) ); return root. Node; Create several additional Default. Mutable. Tree. Nodes for other eras in the history of philosophy and for philosophers in those eras. Fig. 3. 17 Philosophers. JTre e application demonstrating Jtree and Default. Tree. Model. } // end method create. Philosopher. Tree // execute application public static void main( String args[] ) { new Philosophers. JTree(); } Lines 141 -189 } 2002 Prentice Hall. All rights reserved.
Outline Fig. 3. 17 Philosophers. JTre e application demonstrating Jtree and Default. Tree. Model. Program output 2002 Prentice Hall. All rights reserved.
3. 6. 2 Custom Tree. Model Implementation • Implement interface Tree. Model – Example: File. System. Model 2002 Prentice Hall. All rights reserved.
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 Outline // File. System. Model. java // Tree. Model implementation using File objects as tree nodes. package com. deitel. advjhtp 1. mvc. tree. filesystem; // Java core packages import java. io. *; import java. util. *; // Java extension packages import javax. swing. *; import javax. swing. tree. *; import javax. swing. event. *; public class File. System. Model implements Tree. Model { // hierarchy root private File root; Fig. 3. 18 File. System. Model implementation of interface File. System. Model implements. Tree. Model to interface. represent a file system. // Tree. Model. Listeners private Vector listeners = new Vector(); Line 14 // File. System. Model constructor Lines public File. System. Model( File root. Directory ) { Constructor takes a File argument root = root. Directory; Lines for the File. System. Model root. } // get hierarchy root (root directory) public Object get. Root() { Returns the return root; root node. } 23 -26 29 -32 File. System. Model’s 2002 Prentice Hall. All rights reserved.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 Outline Method get. Child returns argument parent’s child node at the given index. // get parent's child at given index public Object get. Child( Object parent, int index ) { // get parent File object File directory = ( File ) parent; // get list of files in parent directory String[] children = directory. list(); // return File at given index and override to. String // method to return only the File's name return new Tree. File( directory, children[ index ] ); } // get parent's number of children public int get. Child. Count( Object parent ) { // get parent File object File file = ( File ) parent; // get number of files in directory if ( file. is. Directory() ) { Fig. 3. 18 File. System. Model implementation Method get. Child. Count of interface returns the number of children to Tree. Model contained in argument parent. represent a file system. Lines 35 -46 String[] file. List = file. list(); if ( file. List != null ) return file. list(). length; Lines 49 -64 } return 0; // child. Count is 0 for files } 2002 Prentice Hall. All rights reserved.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 Outline Object // return true if node is a file, false if it is a. Method directory is. Leaf determines if public boolean is. Leaf( Object node ) argument node is a leaf node. { File file = ( File ) node; return file. is. File(); } // get numeric index of given child node public int get. Index. Of. Child( Object parent, Object child ) { Fig. 3. 18 Method get. Index. Of. Child // get parent File object File. System. Model File directory = ( File ) parent; returns argument child’s index // get child File object File file = ( File ) child; // get File list in directory String[] children = directory. list(); in the given parent node. implementation of interface Tree. Model to represent a file system. // search File list for given child for ( int i = 0; i < children. length; i++ ) { if ( file. get. Name(). equals( children[ i ] ) ) { // return matching File's index return i; } This for loop search through the list for. Lines the given 67 -71 child Lines 74 -98 Lines 86 -93 } return -1; // indicate child index not found } // end method get. Index. Of. Child 2002 Prentice Hall. All rights reserved.
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 Outline // invoked by delegate if value of Object at given // Tree. Path changes Method value. For. Path. Changed public void value. For. Path. Changed( Tree. Path path, is invoked by JTree delegate when Object value ) { the user edits a node in the tree. // get File object that was changed File old. File = ( File ) path. get. Last. Path. Component(); // get parent directory of changed File String file. Parent. Path = old. File. get. Parent(); // get value of new. File. Name entered by user String new. File. Name = ( String ) value; Fig. 3. 18 Invokes method File. System. Model get. Last. Path. Component implementation of class Tree. Path to obtain of interface the File object to rename. to Tree. Model represent // create File object with new. File. Name for system. // renaming old. File Create File object target. File = new File( using the new file name. file. Parent. Path, new. File. Name ); a file Lines 101 -135 // rename old. File to target. File old. File. rename. To( target. File ); // get File object for parent directory File parent = new File( file. Parent. Path ); Invokes method rename. To of class File 105 to rename old. File to Line target. File. Create a File object for the Lines 115 -116 renamed file’s parent directory. // create int array for renamed File's index int[] changed. Children. Indices = { get. Index. Of. Child( parent, target. File) }; // create Object array containing only renamed File Object[] changed. Children = { target. File }; Line 119 Line 122 2002 Prentice Hall. All rights reserved.
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 // notify Tree. Model. Listeners of node change fire. Tree. Nodes. Changed ( path. get. Parent. Path(), changed. Children. Indices , changed. Children ); Outline Invoke method fire. Tree. Nodes. Changed to issue the Tree. Model. Event. } // end method value. For. Path. Changed // notify Tree. Model. Listeners that children of parent at Fig. 3. 18 // given Tree. Path with given indices were changed private void fire. Tree. Nodes. Changed( Tree. Path parent. Path, File. System. Model int[] indices, Object[] children ) implementation Method fire. Tree. Nodes. Changed { of interface // create Tree. Model. Event to indicate node change issues a Tree. Model. Event to all Tree. Model. Event event = new Tree. Model. Event( this, Create the Tree. Model event to registered Tree. Model. Listeners, parent. Path, indices, children ); Iterator iterator = listeners. iterator(); Tree. Model. Listener listener = null; represent a file with the given data. indicating that event nodes in the system. Tree. Model have changed. This while loop iterates through the list of Tree. Model. Listeners, sending Lines 132 -133 the Tree. Model. Event to each. // send Tree. Model. Event to each listener while ( iterator. has. Next() ) { listener = ( Tree. Model. Listener ) iterator. next(); listener. tree. Nodes. Changed( event ); } } // end method fire. Tree. Nodes. Changed // add given Tree. Model. Listener public void add. Tree. Model. Listener( Tree. Model. Listener listener ) { listeners. add( listener ); } Lines 139 -154 Lines 143 -144 Method add. Tree. Model. Listener Lines 150 -153 allow Tree. Model. Listeners to register for Tree. Model. Events. Lines 157 -161 2002 Prentice Hall. All rights reserved.
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 // remove given Tree. Model. Listener public void remove. Tree. Model. Listener ( Tree. Model. Listener listener ) { listeners. remove( listener ); } Outline Method remove. Tree. Model. Listener allow Tree. Model. Listeners to unregister for Tree. Model. Events. // Tree. File is a File subclass that overrides method // to. String to return only the File name. Inner-class private class Tree. File extends File { // Tree. File constructor public Tree. File( File parent, String child ) { super( parent, child ); } // override method to. String to return only the // and not the full path public String to. String() { return get. Name(); } } // end inner class Tree. File } Tree. File overrides method to. String of superclass File. Fig. 3. 18 File. System. Model implementation of interface Tree. Model to File name represent a file system. Lines 164 -168 Lines 172 -186 2002 Prentice Hall. All rights reserved.
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 // File. Tree. Frame. java // JFrame for displaying file system contents in a JTree // using a custom Tree. Model. package com. deitel. advjhtp 1. mvc. tree. filesystem; Outline // Java core packages import java. io. *; import java. awt. event. *; // Java extension packages import javax. swing. *; import javax. swing. tree. *; import javax. swing. event. *; // File. System. Model Tree. Model implementation private File. System. Model file. System. Model ; Fig. 3. 19 File. Tree. Frame application for browsing and editing a file system using JTree and File. System. Model. // JText. Area for displaying selected file's details private JText. Area file. Details. Text. Area ; Lines 33 -34 public class File. Tree. Frame extends JFrame { // JTree for displaying file system private JTree file. Tree; // File. Tree. Frame constructor public File. Tree. Frame( String directory ) { super( "JTree File. System Viewer" ); // create JText. Area for displaying File information file. Details. Text. Area = new JText. Area(); file. Details. Text. Area. set. Editable( false ); Create the uneditable JText. Area for displaying file information. 2002 Prentice Hall. All rights reserved.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 // create File. System. Model for given directory file. System. Model = new File. System. Model( new File( directory ) ); Outline Create a File. System. Model whose root is directory. Creates a JTree for the Fig. 3. 19 File. System. Model. File. Tree. Frame // make JTree editable for renaming Files Sets the JTree’s editable property application for file. Tree. set. Editable( true ); to true, to allow users to rename browsing and files displayed in the JTree. // add a Tree. Selection. Listener editing a file. Tree. add. Tree. Selection. Listener ( Create a Tree. Selection. Listener system using to new Tree. Selection. Listener() { listen for Tree. Selection. Events in JTree and // display details of newly selected File thewhen JTree. File. System. Model. // create JTree for File. System. Model file. Tree = new JTree( file. System. Model ); // selection changes public void value. Changed( Tree. Selection. Event event ) { Get the selected File file = ( File ) file. Tree. get. Last. Selected. Path. Component (); file. Details. Text. Area. set. Text( get. File. Details ( file ) ); } } ); // end add. Tree. Selection. Listener Lines 37 -38 File object from the JTree. Line 41 Line 44 Lines 47 -62 Lines 55 -56 // put file. Tree and file. Details. Text. Area in a JSplit. Pane Create a JSplit. Pane to separate JSplit. Pane split. Pane = new JSplit. Pane( the JTree and JText. Area. JSplit. Pane. HORIZONTAL_SPLIT, true, Lines 65 -69 new JScroll. Pane( file. Tree ), new JScroll. Pane( file. Details. Text. Area ) ); get. Content. Pane(). add( split. Pane ); 2002 Prentice Hall. All rights reserved.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 set. Default. Close. Operation ( EXIT_ON_CLOSE ); set. Size( 640, 480 ); set. Visible( true ); Outline } // build a String to display file details private String get. File. Details( File file ) { // do not return details for null Files if ( file == null ) return ""; } Method get. File. Details takes a File argument and returns a String containing the File’s name, path and length. Fig. 3. 19 File. Tree. Frame // put File information in a String. Buffer buffer = new String. Buffer(); application for buffer. append( "Name: " + file. get. Name() + "n" ); browsing and buffer. append( "Path: " + file. get. Path() + "n" ); editing a file buffer. append( "Size: " + file. length() + "n" ); system using return buffer. to. String(); JTree and File. System. Model. // execute application public static void main( String args[] ) { // ensure that user provided directory name if ( args. length != 1 ) System. err. println( "Usage: java File. Tree. Frame <path>" ); Lines 78 -91 // start application using provided directory name else new File. Tree. Frame( args[ 0 ] ); } } 2002 Prentice Hall. All rights reserved.
Outline Fig. 3. 19 File. Tree. Frame application for browsing and editing a file system using JTree and File. System. Model. Program output 2002 Prentice Hall. All rights reserved.