Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Account Application
// Account.java
// Account is an Observable class that represents a bank
// account in which funds may be deposited or withdrawn.
package com.deitel.advjhtp1.mvc.account;
// Java core packages
import java.util.Observable;
public class Account extends Observable {
private double balance;
private String name;
public Account( String accountName, double openingDeposit )
name = accountName;
setBalance( openingDeposit );
}
private void setBalance( double accountBalance )
balance = accountBalance;
{
{
// call setChanged before notifyObservers to indicate model has
setChanged();
// changed
notifyObservers();// notify Observers that model has changed
}
public double getBalance()
{ return balance;
}
public void withdraw( double amount ) throws IllegalArgumentException
if ( amount < 0 )
throw new IllegalArgumentException(
"Cannott withdraw negative amount" )
setBalance( getBalance() - amount );
}
{
public void deposit( double amount ) throws IllegalArgumentException {
if ( amount < 0 )
throw new IllegalArgumentException(
"Cannot deposit negative amount" );
setBalance( getBalance() + amount );
}
public String getName() { return name;
}
}
// AbstractAccountView.java
// AbstractAccountView is an abstract class that represents
// a view of an Account.
package com.deitel.advjhtp1.mvc.account;
import
import
import
import
java.util.*;
java.awt.*;
javax.swing.JPanel;
javax.swing.border.*;
public abstract class AbstractAccountView extends JPanel implements Observer {
private Account account;
public AbstractAccountView( Account observableAccount )
throws NullPointerException
{
if ( observableAccount == null )
throw new NullPointerException();
account = observableAccount;
// register as an Observer to receive account updates
account.addObserver( this );
setBackground( Color.white );
setBorder( new MatteBorder( 1, 1, 1, 1, Color.black ) );
}
public Account getAccount()
{ return account;
}
protected abstract void updateDisplay();
// receive updates from Observable Account
public void update( Observable observable, Object object ) {
updateDisplay();
}
}
// AccountTextView.java
// AccountTextView is an AbstractAccountView subclass
// that displays an Account balance in a JTextField.
package com.deitel.advjhtp1.mvc.account;
import java.util.*;
import java.text.NumberFormat;
import javax.swing.*;
public class AccountTextView extends AbstractAccountView {
private JTextField balanceTextField = new JTextField( 10 );
private NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
public AccountTextView( Account account )
super( account );
balanceTextField.setEditable( false );
{
// lay out components
add( new JLabel( "Balance: " ) );
add( balanceTextField );
updateDisplay();
}
public void updateDisplay()
{
// set text in balanceTextField to formatted balance
balanceTextField.setText( moneyFormat.format(
getAccount().getBalance() ) );
}
}
// AccountBarGraphView.java
// AccountBarGraphView is an AbstractAccountView subclass
// that displays an Account balance as a bar graph.
package com.deitel.advjhtp1.mvc.account;
import java.awt.*;
import javax.swing.*;
public class AccountBarGraphView extends AbstractAccountView {
public AccountBarGraphView( Account account )
{
super( account );
// draw Account balance as a bar graph
public void paintComponent( Graphics g )
{
super.paintComponent( g );
double balance = getAccount().getBalance();
// calculate integer height for bar graph (graph
// is 200 pixels wide and represents Account balances
// from -$5,000.00to +$5,000.00)
int barLength = ( int ) ( ( balance / 10000.0 ) * 200 );
}
// if balance is positive, draw graph in black
if ( balance >= 0.0 ) {
g.setColor( Color.black );
g.fillRect( 105, 15, barLength, 20 );
}
// if balance is negative, draw graph in red
else {
g.setColor( Color.red );
g.fillRect( 105 + barLength, 15, -barLength, 20 );
}
g.setColor( Color.black ); // draw vertical and horizontal axes
g.drawLine( 5, 25, 205, 25 );
g.drawLine( 105, 5, 105, 45 );
g.setFont( new Font( "SansSerif", Font.PLAIN, 10 ) ); // draw graph labels
g.drawString( "-$5,000", 5, 10 );
g.drawString( "$0", 110, 10 );
g.drawString( "+$5,000", 166, 10 );
} // end method paintComponent
public void updateDisplay()
{
repaint();
public Dimension getPreferredSize()
{ return new Dimension( 210, 50 );
public Dimension getMinimumSize()
public Dimension getMaximumSize()
}
{
{
return getPreferredSize();
return getPreferredSize();
}
}
}
}
// AssetPieChartView.java
// AssetPieChartView is an AbstractAccountView subclass that
// displays multiple asset Account balances as a pie chart.
package com.deitel.advjhtp1.mvc.account;
import
import
import
import
import
java.awt.*;
java.util.*;
java.util.List;
javax.swing.*;
javax.swing.border.*;
public class AssetPieChartView extends JPanel
implements Observer {
private List accounts = new ArrayList(); //observed accounts
private Map colors = new HashMap();
// for drawing pie chart wedges
public void addAccount( Account account )
{
if ( account == null ) // do not add null Accounts
throw new NullPointerException();
accounts.add( account );
// add Color to Hashtable for drawing Account's wedge
colors.put( account, getRandomColor() );
account.addObserver( this ); // register as Observer to receive Account updates
repaint();
}
public void removeAccount( Account account )
{
account.deleteObserver( this ); // stop receiving updates from given Account
accounts.remove( account ); // remove Account from accounts Vector
colors.remove( account ); // remove Account's Color from Hashtable
repaint();
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
drawPieChart( g );
drawLegend( g );
}
// draw Account balances in a pie chart
private void drawPieChart( Graphics g )
{
double totalBalance = getTotalBalance();
double percentage = 0.0;
int startAngle = 0;
int arcAngle = 0;
Iterator accountIterator = accounts.iterator();
Account account = null;
while ( accountIterator.hasNext() ) { // draw pie wedge for each Account
account = ( Account ) accountIterator.next();
if ( !includeAccountInChart( account ) )
continue;
percentage = account.getBalance() / totalBalance;
arcAngle = ( int ) Math.round( percentage * 360 );
g.setColor( ( Color ) colors.get( account ) );
g.fillArc( 5, 5, 100, 100, startAngle, arcAngle );
startAngle += arcAngle;
}
} // end method drawPieChart
private void drawLegend( Graphics g )
{
Iterator accountIterator = accounts.iterator();
Account account = null;
Font font = new Font( "SansSerif", Font.BOLD, 12 );
g.setFont( font );
// get FontMetrics for calculating offsets and positioning descriptions
FontMetrics metrics = getFontMetrics( font );
int ascent = metrics.getMaxAscent();
int offsetY = ascent + 2;
// draw description for each Account
for ( int i = 1; accountIterator.hasNext(); i++ ) {
account = ( Account ) accountIterator.next();
g.setColor( ( Color ) colors.get( account ) );
g.fillRect( 125, offsetY * i, ascent, ascent );
g.setColor( Color.black );
g.drawString( account.getName(), 140, offsetY * i + ascent );
}
} // end method drawLegend
// get combined balance of all observed Accounts
private double getTotalBalance()
{
double sum = 0.0;
Iterator accountIterator = accounts.iterator();
Account account = null;
while ( accountIterator.hasNext() ) {
account = ( Account ) accountIterator.next();
if ( includeAccountInChart( account ) )
sum += account.getBalance();
}
return sum;
}
// return true if given Account should be included in pie chart
protected boolean includeAccountInChart( Account account )
{
// include only Asset accounts (Accounts with positive balances)
return account.getBalance() > 0.0;
}
// get a random Color for drawing pie wedges
private Color getRandomColor()
{
// calculate random red, green and blue values
int red = ( int ) ( Math.random() * 256 );
int green = ( int ) ( Math.random() * 256 );
int blue = ( int ) ( Math.random() * 256 );
return new Color( red, green, blue );
}
// receive updates from Observable Account
public void update( Observable observable, Object object )
public Dimension getPreferredSize()
{
public Dimension getMinimumSize()
{
public Dimension getMaximumSize()
{
{
repaint();
return new Dimension( 210, 110 );
return getPreferredSize();
}
return getPreferredSize();
}
}
}
}
// AccountController.java
// AccountController is a controller for Accounts. It provides
// a JTextField for inputting a deposit or withdrawal amount
// and JButtons for depositing or withdrawing funds.
package com.deitel.advjhtp1.mvc.account;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AccountController extends JPanel {
private Account account; // Account to control
private JTextField amountTextField;
public AccountController( Account controlledAccount )
{
super();
account = controlledAccount;
amountTextField = new JTextField( 10 );
JButton depositButton = new JButton( "Deposit" );
depositButton.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event ) {
try {
account.deposit( Double.parseDouble(
amountTextField.getText() ) );
}
catch ( NumberFormatException exception ) {
JOptionPane.showMessageDialog (
AccountController.this,
"Please enter a valid amount", "Error",
JOptionPane.ERROR_MESSAGE );
}
} // end method actionPerformed
}
);
JButton withdrawButton = new JButton( "Withdraw" );
withdrawButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
try {
account.withdraw( Double.parseDouble(amountTextField.getText() ) );
}
catch ( NumberFormatException exception ) {
JOptionPane.showMessageDialog (
AccountController.this,
"Please enter a valid amount", "Error",
JOptionPane.ERROR_MESSAGE );
}
} // end method actionPerformed
}
);
// lay out controller components
setLayout( new FlowLayout() );
add( new JLabel( "Amount: " ) );
add( amountTextField );
add( depositButton );
add( withdrawButton );
}
}
// AccountManager.java
// AccountManager is an application that uses the MVC design
// pattern to manage bank Account information.
package com.deitel.advjhtp1.mvc.account;
import
import
import
import
java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.border.*;
public class AccountManager extends JFrame {
public AccountManager()
{
super( "Account Manager" );
// create account1 with initial balance
Account account1 = new Account( "Account 1", 1000.00 );
JPanel account1Panel = createAccountPanel( account1 );
// create account2 with initial balance
Account account2 = new Account( "Account 2", 3000.00 );
JPanel account2Panel = createAccountPanel( account2 );
// create AccountPieChartView to show Account pie chart
AssetPieChartView pieChartView = new AssetPieChartView();
// add both Accounts to AccountPieChartView
pieChartView.addAccount( account1 );
pieChartView.addAccount( account2 );
JPanel pieChartPanel = new JPanel();
pieChartPanel.setBorder( new TitledBorder( "Assets" ) );
pieChartPanel.add( pieChartView );
// lay out account1, account2 and pie chart components
Container contentPane = getContentPane();
contentPane.setLayout( new GridLayout( 3, 1 ) );
contentPane.add( account1Panel );
contentPane.add( account2Panel );
contentPane.add( pieChartPanel );
setSize( 425, 450 );
} // end AccountManager constructor
// create GUI components for given Account
private JPanel createAccountPanel( Account account )
{
JPanel accountPanel = new JPanel();
accountPanel.setBorder( new TitledBorder( account.getName() ) );
AccountTextView accountTextView = new AccountTextView( account );
AccountBarGraphView accountBarGraphView = new AccountBarGraphView( account );
AccountController accountController = new AccountController( account );
accountPanel.add( accountController );
accountPanel.add( accountTextView );
accountPanel.add( accountBarGraphView );
return accountPanel;
} // end method getAccountPanel
// execute application
public static void main( String args[] )
{
AccountManager manager = new AccountManager();
manager.setDefaultCloseOperation( EXIT_ON_CLOSE );
manager.setVisible( true );
}
}
JList Application
// PhilosophersJList.java
// MVC architecture using JList with a DefaultListModel
package com.deitel.advjhtp1.mvc.list;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PhilosophersJList extends JFrame {
private DefaultListModel philosophers;
private JList list;
// PhilosophersJList constructor
public PhilosophersJList()
{
super( "Favorite Philosophers" );
// create a DefaultListModel to store philosophers
philosophers = new DefaultListModel();
philosophers.addElement( "Socrates" );
philosophers.addElement( "Plato" );
philosophers.addElement( "Aristotle" );
philosophers.addElement( "St. Thomas Aquinas" );
philosophers.addElement( "Soren Kierkegaard" );
philosophers.addElement( "Immanuel Kant" );
philosophers.addElement( "Friedrich Nietzsche" );
philosophers.addElement( "Hannah Arendt" );
// create a JList for philosophers DefaultListModel
list = new JList( philosophers );
list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
JButton addButton = new JButton( "Add Philosopher" );
addButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event )
{
String name = JOptionPane.showInputDialog(PhilosophersJList.this, "Enter Name" );
philosophers.addElement( name ); // add new philosopher to model
}
});
JButton removeButton = new JButton( "Remove Selected Philosopher" );
removeButton.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event ) {
philosophers.removeElement(list.getSelectedValue());
}
});
// lay out GUI components
JPanel inputPanel = new JPanel();
inputPanel.add( addButton );
inputPanel.add( removeButton );
Container container = getContentPane();
container.add( list, BorderLayout.CENTER );
container.add( inputPanel, BorderLayout.NORTH );
setDefaultCloseOperation( EXIT_ON_CLOSE );
setSize( 400, 300 );
setVisible( true );
} // end PhilosophersJList constructor
// execute application
public static void main( String args[] )
new PhilosophersJList();
}
{
}
JTable Application
// PhilosophersJTable.java
// MVC architecture using JTable with a DefaultTableModel
package com.deitel.advjhtp1.mvc.table;
import
import
import
import
java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.table.*;
public class PhilosophersJTable extends JFrame {
private DefaultTableModel philosophers;
private JTable table;
public PhilosophersJTable()
{
super( "Favorite Philosophers" );
// create a DefaultTableModel to store philosophers
philosophers = new DefaultTableModel();
philosophers.addColumn( "First Name" );
philosophers.addColumn( "Last Name" );
philosophers.addColumn( "Years" );
String[] socrates = { "Socrates", "", "469-399 B.C." };
philosophers.addRow( socrates );
String[] plato = { "Plato", "", "428-347 B.C." };
philosophers.addRow( plato );
String[] aquinas = { "Thomas", "Aquinas", "1225-1274" };
philosophers.addRow( aquinas );
String[] kierkegaard = { "Soren", "Kierkegaard", "1813-1855" };
philosophers.addRow( kierkegaard );
String[] kant = { "Immanuel", "Kant", "1724-1804" };
philosophers.addRow( kant );
String[] nietzsche = { "Friedrich", "Nietzsche", "1844-1900" };
philosophers.addRow( nietzsche );
String[] arendt = { "Hannah", "Arendt", "1906-1975" };
philosophers.addRow( arendt );
// create a JTable for philosophers DefaultTableModel
table = new JTable( philosophers );
JButton addButton = new JButton( "Add Philosopher" );
addButton.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event ) {
String[] philosopher = { "", "", "" };
// add empty philosopher row to model
philosophers.addRow( philosopher );
}
});
JButton removeButton = new JButton( "Remove Selected Philosopher" );
removeButton.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event ) {
philosophers.removeRow( table.getSelectedRow() );
}
});
// lay out GUI components
JPanel inputPanel = new JPanel();
inputPanel.add( addButton );
inputPanel.add( removeButton );
Container container = getContentPane();
container.add( new JScrollPane( table ), BorderLayout.CENTER );
container.add( inputPanel, BorderLayout.NORTH );
setDefaultCloseOperation( EXIT_ON_CLOSE );
setSize( 400, 300 );
setVisible( true );
} // end PhilosophersJTable constructor
// execute application
public static void main( String args[] )
new PhilosophersJTable();
}
{
}
JTree Application with DefaultTreeModel
// PhilosophersJTree.java
// MVC architecture using JTree with a DefaultTreeModel
package com.deitel.advjhtp1.mvc.tree;
import
import
import
import
import
java.awt.*;
java.awt.event.*;
java.util.*;
javax.swing.*;
javax.swing.tree.*;
public class PhilosophersJTree extends JFrame {
private JTree tree;
private DefaultTreeModel philosophers;
private DefaultMutableTreeNode rootNode;
public PhilosophersJTree()
{
super( "Favorite Philosophers" );
// get tree of philosopher DefaultMutableTreeNodes
DefaultMutableTreeNode philosophersNode = getPhilosopherTree();
// create philosophers DefaultTreeModel
philosophers = new DefaultTreeModel( philosophersNode );
// create JTree for philosophers DefaultTreeModel
tree = new JTree( philosophers );
JButton addButton = new JButton( "Add Philosopher" );
addButton.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event ) {
addPhilosopher();
}
});
JButton removeButton = new JButton( "Remove Selected Philosopher" );
removeButton.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event ) {
removeSelectedPhilosopher();
}
});
// lay out GUI components
JPanel inputPanel = new JPanel();
inputPanel.add( addButton );
inputPanel.add( removeButton );
Container container = getContentPane();
container.add( new JScrollPane( tree ), BorderLayout.CENTER );
container.add( inputPanel, BorderLayout.NORTH );
setDefaultCloseOperation( EXIT_ON_CLOSE );
setSize( 400, 300 );
setVisible( true );
} // end PhilosophersJTree constructor
// add new philosopher to selected era
private void addPhilosopher()
{
DefaultMutableTreeNode parent = getSelectedNode();// get selected era
// ensure user selected era first
if ( parent == null ) {
JOptionPane.showMessageDialog(PhilosophersJTree.this, "Select an era.",
"Error", JOptionPane.ERROR_MESSAGE );
return;
}
// prompt user for philosopher's name
String name = JOptionPane.showInputDialog(PhilosophersJTree.this, "Enter Name:" );
// add new philosopher to selected era
philosophers.insertNodeInto(new DefaultMutableTreeNode( name ),
parent, parent.getChildCount() );
} // end method addPhilosopher
// remove currently selected philosopher
private void removeSelectedPhilosopher()
{
// get selected node
DefaultMutableTreeNode selectedNode = getSelectedNode();
// remove selectedNode from model
if ( selectedNode != null )
philosophers.removeNodeFromParent( selectedNode );
}
// get currently selected node
private DefaultMutableTreeNode getSelectedNode()
{
// get selected DefaultMutableTreeNode
return (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
}
// get tree of philosopher DefaultMutableTreeNodes
private DefaultMutableTreeNode getPhilosopherTree()
{
// create rootNode
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode( "Philosophers" );
// Ancient philosophers
DefaultMutableTreeNode ancient = new DefaultMutableTreeNode( "Ancient" );
rootNode.add( ancient );
ancient.add( new DefaultMutableTreeNode( "Socrates" ) );
ancient.add( new DefaultMutableTreeNode( "Plato" ) );
ancient.add( new DefaultMutableTreeNode( "Aristotle" ) );
// Medieval philosophers
DefaultMutableTreeNode medieval = new DefaultMutableTreeNode( "Medieval" );
rootNode.add( medieval );
medieval.add( new DefaultMutableTreeNode("St. Thomas Aquinas" ) );
// Renaissance philosophers
DefaultMutableTreeNode renaissance = new DefaultMutableTreeNode( "Renaissance" );
rootNode.add( renaissance );
renaissance.add( new DefaultMutableTreeNode( "Thomas More" ) );
// Early Modern philosophers
DefaultMutableTreeNode earlyModern = new DefaultMutableTreeNode( "Early Modern" );
rootNode.add( earlyModern );
earlyModern.add( new DefaultMutableTreeNode( "John Locke" ) );
// Enlightenment Philosophers
DefaultMutableTreeNode enlightenment = new DefaultMutableTreeNode("Enlightenment");
rootNode.add( enlightenment );
enlightenment.add( new DefaultMutableTreeNode( "Immanuel Kant" ) );
// 19th Century Philosophers
DefaultMutableTreeNode nineteenth = new DefaultMutableTreeNode( "19th Century" );
rootNode.add( nineteenth );
nineteenth.add( new DefaultMutableTreeNode( "Soren Kierkegaard" ) );
nineteenth.add( new DefaultMutableTreeNode( "Friedrich Nietzsche" ) );
// 20th Century Philosophers
DefaultMutableTreeNode twentieth = new DefaultMutableTreeNode( "20th Century" );
rootNode.add( twentieth );
twentieth.add( new DefaultMutableTreeNode( "Hannah Arendt" ) );
return rootNode;
} // end method getPhilosopherTree
// execute application
public static void main( String args[] )
new PhilosophersJTree();
}
{
}
Tree Application with a Custom TreeModel Implementation
// FileSystemModel.java
// TreeModel implementation using File objects as tree nodes.
package com.deitel.advjhtp1.mvc.tree.filesystem;
import
import
import
import
import
java.io.*;
java.util.*;
javax.swing.*;
javax.swing.tree.*;
javax.swing.event.*;
public class FileSystemModel implements TreeModel {
private File root;
// hierarchy root
private Vector listeners = new Vector(); // TreeModelListeners
public FileSystemModel( File rootDirectory ) {
root = rootDirectory;
}
public Object getRoot()
{
return root;
}
public Object getChild( 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 toString
// method to return only the File's name
return new TreeFile( directory, children[ index ] );
}
public int getChildCount( Object parent )
// get parent File object
File file = ( File ) parent;
{
// parent's number of children
// get number of files in directory
if ( file.isDirectory() ) {
String[] fileList = file.list();
if ( fileList != null )
return file.list().length;
}
return 0; // childCount is 0 for files
}
// return true if node is a file, false if it is a directory
public boolean isLeaf( Object node )
{
File file = ( File ) node;
return file.isFile();
}
public int getIndexOfChild( Object parent, Object child )
// get parent File object
File directory = ( File ) parent;
{
// get child File object
File file = ( File ) child;
// get File list in directory
String[] children = directory.list();
// search File list for given child
for ( int i = 0; i < children.length; i++ ) {
if ( file.getName().equals( children[ i ] ) ) {
return i; // return matching File's index
}
}
return -1; // indicate child index not found
} // end method getIndexOfChild
// invoked by delegate if value of Object at given TreePath changes:
public void valueForPathChanged( TreePath path, Object value )
{
// get File object that was changed
File oldFile = ( File ) path.getLastPathComponent();
// get parent directory of changed File
String fileParentPath = oldFile.getParent();
// get value of newFileName entered by user
String newFileName = ( String ) value;
// create File object with newFileName to rename oldFile
File targetFile = new File( fileParentPath, newFileName );
// rename oldFile to targetFile
oldFile.renameTo( targetFile );
// get File object for parent directory
File parent = new File( fileParentPath );
// create int array for renamed File's index
int[] changedChildrenIndices = { getIndexOfChild( parent, targetFile) };
// create Object array containing only renamed File
Object[] changedChildren = { targetFile };
// notify TreeModelListeners of node change
fireTreeNodesChanged( path.getParentPath(), changedChildrenIndices,
changedChildren );
} // end method valueForPathChanged
// notify TreeModelListeners that children of parent at
// given TreePath with given indices were changed
private void fireTreeNodesChanged( TreePath parentPath,
int[] indices, Object[] children )
{
// create TreeModelEvent to indicate node change
TreeModelEvent event = new TreeModelEvent( this, parentPath, indices, children );
Iterator iterator = listeners.iterator();
TreeModelListener listener = null;
// send TreeModelEvent to each listener
while ( iterator.hasNext() ) {
listener = ( TreeModelListener ) iterator.next();
listener.treeNodesChanged( event );
}
} // end method fireTreeNodesChanged
public void addTreeModelListener( TreeModelListener listener )
listeners.add( listener );
}
{
public void removeTreeModelListener( TreeModelListener listener ) {
listeners.remove( listener );
}
// TreeFile = File subclass that overrides method toString to return
//only the File name.
private class TreeFile extends File {
public TreeFile( File parent, String child )
{ super( parent, child );
}
// override method toString to return only the File name
// and not the full path
public String toString()
{
return getName();
}
} // end inner class TreeFile
}
// FileTreeFrame.java
// JFrame for displaying file system contents in a JTree using a custom TreeModel.
package com.deitel.advjhtp1.mvc.tree.filesystem;
import
import
import
import
import
import
java.io.*;
java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.tree.*;
javax.swing.event.*;
public class FileTreeFrame extends JFrame {
private JTree fileTree; // JTree for displaying file system
// FileSystemModel TreeModel implementation
private FileSystemModel fileSystemModel;
private JTextArea fileDetailsTextArea; //for displaying selected file's details
public FileTreeFrame( String directory )
super( "JTree FileSystem Viewer" );
{
// create JTextArea for displaying File information
fileDetailsTextArea = new JTextArea();
fileDetailsTextArea.setEditable( false );
// create FileSystemModel for given directory
fileSystemModel = new FileSystemModel( new File( directory ) );
fileTree = new JTree( fileSystemModel ); // create JTree for FileSystemModel
fileTree.setEditable( true );
// for renaming Files
fileTree.addTreeSelectionListener( new TreeSelectionListener() {
// display details of newly selected File when selection changes
public void valueChanged( TreeSelectionEvent event ) {
File file = ( File ) fileTree.getLastSelectedPathComponent();
fileDetailsTextArea.setText( getFileDetails( file ) );
}
}); // end addTreeSelectionListener
// put fileTree and fileDetailsTextArea in a JSplitPane
JSplitPane splitPane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT, true,
new JScrollPane( fileTree ),
new JScrollPane( fileDetailsTextArea ) );
getContentPane().add( splitPane );
setDefaultCloseOperation( EXIT_ON_CLOSE );
setSize( 640, 480 );
setVisible( true );
}
// build a String to display file details
private String getFileDetails( File file )
// do not return details for null Files
if ( file == null )
return "";
{
// put File information in a StringBuffer
StringBuffer buffer = new StringBuffer();
buffer.append( "Name: " + file.getName() + "\n" );
buffer.append( "Path: " + file.getPath() + "\n" );
buffer.append( "Size: " + file.length() + "\n" );
return buffer.toString();
}
// execute application
public static void main( String args[] )
{
// ensure that user provided directory name
if ( args.length != 1 )
System.err.println(
"Usage: java FileTreeFrame <path>" );
// start application using provided directory name
else
new FileTreeFrame( args[ 0 ] );
}
}