Java Swing V2.1 Workshop Solutions

  • Uploaded by: Muhammad Imran Saeed
  • 0
  • 0
  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Java Swing V2.1 Workshop Solutions as PDF for free.

More details

  • Words: 10,203
  • Pages: 60
Java Swing Workshop Solutions

Java Swing: Workshop Solutions

Table of Contents

Workshop 2: Using Basic Components ........................................................................................i Workshop 3: Using Swing Containers .......................................................................................vii Workshop 4: Using Menus & ToolBars .....................................................................................xiv Workshop 5: Using Common Dialogs .....................................................................................xxiii Workshop 6: Using Borders ...................................................................................................xxxiv Workshop 7: Using Internal Frames..........................................................................................xlv Workshop 8: Using a List Model................................................................................................lvii

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page i

Workshop 2: Using Basic Components

SwingApp.java // SwingApp.java // After Basic Components exercise. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingApp { public static void main( String[] args ) { new MainWindow(args); } } class MainWindow extends Frame { private ToolBar toolBar; private StatusBar statusBar = new StatusBar(); private JTextArea textArea = new JTextArea(); // Constructor public MainWindow(String[] args) { super("Studentsoft Super System"); initLayout(); // A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { quit(0); } } ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show();

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page ii

// Pop login dialog if "login" passed as 1st argument. // If user cancels or closes, close the application. if( args.length > 0 && args[0].toUpperCase().equals("LOGIN") ) if( ! login() ) quit(0); showStatus( "Hello!" ); } // login() pops the LoginDialog, returns true if // user clicks OK, false if user clicks Cancel // or closes. private boolean login() { // return true; boolean bOK[] = new boolean[1]; bOK[0] = false; new LoginDialog(bOK); return bOK[0]; } // Private methods private void cut() { textArea.cut(); showStatus("Text cut to clipboard"); } private void copy() { textArea.copy(); showStatus("Text copied to clipboard"); } private void paste() { textArea.paste(); showStatus("Text pasted from clipboard"); } private boolean quit(int retCode) { System.exit(retCode); return true; } private void initLayout() { toolBar = new ToolBar(); // Configure text area textArea.setLineWrap( true ); textArea.setWrapStyleWord( true ); textArea.setToolTipText("Enter / edit text here"); // Configure frame setBounds( 100, 100, 500, 300 ); add( BorderLayout.NORTH , toolBar ); add( BorderLayout.CENTER, textArea ); add( BorderLayout.SOUTH , statusBar ); } private void showStatus( String text ) {

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page iii

statusBar.showStatus( text ); } // INNER CLASSES // Inner class for status bar private class StatusBar extends Panel { private JLabel label = new JLabel( " ", JLabel.LEFT ); public StatusBar() { setLayout( new BorderLayout() ); setBackground( Color.lightGray ); label.setForeground( Color.black ); add( label, BorderLayout.SOUTH ); }

}

public void showStatus( String text ) { label.setText( " " + text ); doLayout(); } // end of StatusBar class

// Inner class for toolbar private class ToolBar extends Panel implements ActionListener { public ToolBar() { JButton btnCut = new JButton("Cut"); btnCut.setActionCommand("cut"); btnCut.setMnemonic('c'); btnCut.setToolTipText("Cut to clipboard"); btnCut.addActionListener( this ); JButton btnCopy = new JButton("Copy"); btnCopy.setActionCommand("copy"); btnCopy.setMnemonic('o'); btnCopy.setToolTipText("Copy to clipboard"); btnCopy.addActionListener( this ); JButton btnPaste = new JButton("Paste"); btnPaste.setActionCommand("paste"); btnPaste.setMnemonic('p'); btnPaste.setToolTipText("Paste from clipboard"); btnPaste.addActionListener( this ); setBackground( Color.lightGray ); setLayout( new FlowLayout( FlowLayout.LEFT )); add( btnCut ); add( btnCopy ); add( btnPaste ); } // Event handling for Cut, Copy and Paste buttons public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("cut") ) cut(); else if( ae.getActionCommand().equals("copy") ) copy(); else if( ae.getActionCommand().equals("paste") ) paste();

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

}

Page iv

} // end of ToolBar class

// Login window private class LoginDialog extends Dialog implements ActionListener { boolean OKflag[]; JLabel labelUID JLabel labelPWD JTextField tfUID JTextField tfPWD JButton btnOK JButton btnCancel

= = = = = =

new new new new new new

JLabel("User ID:", JLabel.RIGHT); JLabel("Password:", JLabel.RIGHT); JTextField(); JTextField(); JButton("OK"); JButton("Cancel");

public LoginDialog( boolean[] OKflagI ) { super( MainWindow.this, "User Login", true ); OKflag = OKflagI; initLayout(); // Set up accelerators & mnemonics // For user ID field, use JTextField.setFocusAccelerator() tfUID.setFocusAccelerator( 'u' ); labelUID.setDisplayedMnemonic( 'u' ); // For password field, use JLabel.setLabelFor() labelPWD.setLabelFor( tfPWD ); labelPWD.setDisplayedMnemonic( 'p' ); // Set up action commands btnOK.setActionCommand("ok"); btnCancel.setActionCommand("cancel"); // Button event handling performed by LoginDialog btnOK.addActionListener( this ); btnCancel.addActionListener( this ); // A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { we.getWindow().dispose(); } } ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); } public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("ok") ) OKflag[0] = true; dispose();

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page v

} private void initLayout() { GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); setLayout( gbl ); setBounds( 100, 100, 300, 200 ); // Size & position dialog setResizable( false ); // Make dialog fixed size // Add UID label to login window gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelUID, gbc ); // apply constraints add( labelUID ); // Add PWD label to login window gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelPWD, gbc ); // apply constraints add( labelPWD ); // Add UID text field to login window gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfUID, gbc ); // apply constraints add( tfUID ); // Add PWD text field to login window gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfPWD, gbc ); // apply constraints add( tfPWD );

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page vi

// Add OK button to login window gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnOK, gbc ); // apply constraints add( btnOK ); // Add Cancel button to login window gbc.gridx = 2; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnCancel, gbc ); // apply constraints add( btnCancel ); tfUID.requestFocus(); } }

// Put focus on ID field

// end of initLayout()

// end of LoginWindow class

}

// end of MainWindow class

// // // // //

FontSetter is a convenience class. Its one static method, setFont(), is used to change the font setting for all components in a container. This is simply to make the font bigger for display purposes; it has no bearing on the exercise.

class FontSetter { // Change the font of the desired component and // all its contained components and menus. public static void setFont( Component c, Font f ) { if( c instanceof JMenu ) { JMenu mnu = (JMenu) c; for(int i = 0; i < mnu.getMenuComponentCount(); i++) setFont( mnu.getMenuComponent(i), f ); } else if( c instanceof Container ) { Container cont = (Container) c; for(int i = 0; i < cont.getComponentCount(); i++) setFont( cont.getComponent(i), f ); } c.setFont( f ); } }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page vii

Workshop 3: Using Swing Containers

SwingApp.Java // SwingApp.java // After Swing Containers exercise. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingApp { public static void main( String[] args ) { new MainWindow(args); } } class MainWindow extends JFrame { private ToolBar toolBar ; private StatusBar statusBar = new StatusBar(); private JTextArea textArea = new JTextArea(); // Constructor public MainWindow(String[] args) { super("Studentsoft Super System"); initLayout(); // Turn off default closing mechanism setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE ); // A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { quit(0); } } ); // Set font of entire frame just before showing.

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page viii

FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); // Pop login dialog if "login" passed as 1st argument. // If user cancels or closes, close the application. if( args.length > 0 && args[0].toUpperCase().equals("LOGIN") ) if( ! login() ) quit(0); showStatus( "Hello!" ); } // login() pops the LoginDialog, returns true if // user clicks OK, false if user clicks Cancel // or closes. private boolean login() { // return true; boolean bOK[] = new boolean[1]; bOK[0] = false; new LoginDialog(bOK); return bOK[0]; } // Private methods private void cut() { textArea.cut(); showStatus("Text cut to clipboard"); } private void copy() { textArea.copy(); showStatus("Text copied to clipboard"); } private void paste() { textArea.paste(); showStatus("Text pasted from clipboard"); } private boolean quit(int retCode) { System.exit(retCode); return true; } private void initLayout() { toolBar = new ToolBar(); // Configure text area textArea.setLineWrap( true ); textArea.setWrapStyleWord( true ); textArea.setToolTipText("Enter / edit text here"); // Configure frame setBounds( 100, 100, 500, 300 ); getContentPane().add( BorderLayout.NORTH , getContentPane().add( BorderLayout.CENTER, getContentPane().add( BorderLayout.SOUTH ,

© 2003 SkillBuilders Inc.

toolBar ); textArea ); statusBar );

V 2.1

Java SWing: Workshop Solutions

Page ix

} private void showStatus( String text ) { statusBar.showStatus( text ); } // INNER CLASSES // Inner class for status bar private class StatusBar extends JPanel { private JLabel label = new JLabel( " ", JLabel.LEFT ); public StatusBar() { setLayout( new BorderLayout() ); setBackground( Color.lightGray ); label.setForeground( Color.black ); add( label, BorderLayout.SOUTH ); }

}

public void showStatus( String text ) { label.setText( " " + text ); doLayout(); } // end of StatusBar class

// Inner class for toolbar private class ToolBar extends JPanel implements ActionListener { public ToolBar() { JButton btnCut = new JButton("Cut"); btnCut.setActionCommand("cut"); btnCut.setMnemonic('c'); btnCut.setToolTipText("Cut to clipboard"); btnCut.addActionListener( this ); JButton btnCopy = new JButton("Copy"); btnCopy.setActionCommand("copy"); btnCopy.setMnemonic('o'); btnCopy.setToolTipText("Copy to clipboard"); btnCopy.addActionListener( this ); JButton btnPaste = new JButton("Paste"); btnPaste.setActionCommand("paste"); btnPaste.setMnemonic('p'); btnPaste.setToolTipText("Paste from clipboard"); btnPaste.addActionListener( this ); setBackground( Color.lightGray ); setLayout( new FlowLayout( FlowLayout.LEFT )); add( btnCut ); add( btnCopy ); add( btnPaste ); } // Event handling for Cut, Copy and Paste buttons public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("cut") ) cut(); else if( ae.getActionCommand().equals("copy") )

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page x

copy(); else if( ae.getActionCommand().equals("paste") ) paste(); }

} // end of ToolBar class

// Login window private class LoginDialog extends JDialog implements ActionListener { boolean OKflag[]; JLabel labelUID JLabel labelPWD JTextField tfUID JTextField tfPWD JButton btnOK JButton btnCancel

= = = = = =

new new new new new new

JLabel("User ID:", JLabel.RIGHT); JLabel("Password:", JLabel.RIGHT); JTextField(); JTextField(); JButton("OK"); JButton("Cancel");

public LoginDialog( boolean[] OKflagI ) { super( MainWindow.this, "User Login", true ); OKflag = OKflagI; initLayout(); // Set up accelerators & mnemonics // For user ID field, use JTextField.setFocusAccelerator() tfUID.setFocusAccelerator( 'u' ); labelUID.setDisplayedMnemonic( 'u' ); // For password field, use JLabel.setLabelFor() labelPWD.setLabelFor( tfPWD ); labelPWD.setDisplayedMnemonic( 'p' ); // Set up action commands btnOK.setActionCommand("ok"); btnCancel.setActionCommand("cancel"); // Button event handling performed by LoginDialog btnOK.addActionListener( this ); btnCancel.addActionListener( this ); /* // A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { we.getWindow().dispose(); } } ); */ // Use default closing mechanism to close dialog setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) );

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xi

show(); } public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("ok") ) OKflag[0] = true; dispose(); } private void initLayout() { GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); getContentPane().setLayout( gbl ); setBounds( 100, 100, 300, 200 ); // Size & position dialog setResizable( false ); // Make dialog fixed size // Add UID label to login window gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelUID, gbc ); // apply constraints getContentPane().add( labelUID ); // Add PWD label to login window gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelPWD, gbc ); // apply constraints getContentPane().add( labelPWD ); // Add UID text field to login window gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfUID, gbc ); // apply constraints getContentPane().add( tfUID ); // Add PWD text field to login window gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1;

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xii

gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfPWD, gbc ); // apply constraints getContentPane().add( tfPWD ); // Add OK button to login window gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnOK, gbc ); // apply constraints getContentPane().add( btnOK ); // Add Cancel button to login window gbc.gridx = 2; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnCancel, gbc ); // apply constraints getContentPane().add( btnCancel ); tfUID.requestFocus(); } }

// Put focus on ID field

// end of initLayout()

// end of LoginWindow class

}

// end of MainWindow class

// // // // //

FontSetter is a convenience class. Its one static method, setFont(), is used to change the font setting for all components in a container. This is simply to make the font bigger for display purposes; it has no bearing on the exercise.

class FontSetter { // Change the font of the desired component and // all its contained components and menus. public static void setFont( Component c, Font f ) { if( c instanceof JMenu ) { JMenu mnu = (JMenu) c; for(int i = 0; i < mnu.getMenuComponentCount(); i++) setFont( mnu.getMenuComponent(i), f ); } else if( c instanceof Container ) { Container cont = (Container) c;

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xiii

for(int i = 0; i < cont.getComponentCount(); i++) setFont( cont.getComponent(i), f ); } c.setFont( f ); } }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xiv

Workshop 4: Using Menus & ToolBars

SwingApp.java // SwingApp.java // After Menu & ToolBar exercise. import import import import

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

public class SwingApp { public static void main( String[] args ) { new MainWindow(args); } } class MainWindow extends JFrame { private ToolBar toolBar ; private StatusBar statusBar = new StatusBar(); private JTextArea textArea = new JTextArea(); private Action actCut, actCopy, actPaste; // Constructor public MainWindow(String[] args) { super("Studentsoft Super System"); initActions(); initLayout(); initMenu(); // Turn off default closing mechanism setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE ); // A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { quit(0);

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xv

} } ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); // Pop login dialog if "login" passed as 1st argument. // If user cancels or closes, close the application. if( args.length > 0 && args[0].toUpperCase().equals("LOGIN") ) if( ! login() ) quit(0); showStatus( "Hello!" ); } // login() pops the LoginDialog, returns true if // user clicks OK, false if user clicks Cancel // or closes. private boolean login() { // return true; boolean bOK[] = new boolean[1]; bOK[0] = false; new LoginDialog(bOK); return bOK[0]; } // Private methods private void cut() { textArea.cut(); showStatus("Text cut to clipboard"); } private void copy() { textArea.copy(); showStatus("Text copied to clipboard"); } private void paste() { textArea.paste(); showStatus("Text pasted from clipboard"); } private boolean quit(int retCode) { System.exit(retCode); return true; } // Set up Action objects private void initActions() { // Action objects for cut, copy, paste: actCut = new AbstractAction("Cut") { public void actionPerformed(ActionEvent ae) { cut(); } }; actCut.putValue(Action.SHORT_DESCRIPTION,

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xvi

"Cut text to clipboard"); actCopy = new AbstractAction("Copy") { public void actionPerformed(ActionEvent ae) { copy(); } }; actCopy.putValue(Action.SHORT_DESCRIPTION, "Copy text to clipboard"); actPaste = new AbstractAction("Paste") { public void actionPerformed(ActionEvent ae) { paste(); } }; actPaste.putValue(Action.SHORT_DESCRIPTION, "Paste text from clipboard"); } private void initLayout() { toolBar = new ToolBar(); // Configure text area textArea.setLineWrap( true ); textArea.setWrapStyleWord( true ); textArea.setToolTipText("Enter / edit text here"); // Configure frame setBounds( 100, 100, 500, 300 ); getContentPane().add( BorderLayout.NORTH , getContentPane().add( BorderLayout.CENTER, getContentPane().add( BorderLayout.SOUTH ,

toolBar ); textArea ); statusBar );

// Create caret listener for textArea to react when // selection changes textArea.addCaretListener( new CaretListener() { public void caretUpdate(CaretEvent e) { boolean isSelection = textArea.getSelectionStart() != textArea.getSelectionEnd(); actCut.setEnabled(isSelection); actCopy.setEnabled(isSelection); } }); } private void initMenu() { // Local inner class for handling menu items class MenuHandler implements ActionListener { public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("FileNew") ) showStatus("New file created"); else if( ae.getActionCommand().equals("FileOpen") ) showStatus("File opened"); else if( ae.getActionCommand().equals("FileSave") ) showStatus("File saved"); else if( ae.getActionCommand().equals("FileExit") )

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xvii

quit( 0 ); // Toggle toolbar visibility else if( ae.getActionCommand().equals("OptionsToolbar") ) { // Get source, cast it as JCheckBoxMenuItem: JCheckBoxMenuItem cbmi = (JCheckBoxMenuItem) ae.getSource(); toolBar.setVisible( cbmi.isSelected() ); getContentPane().doLayout(); } } } // Instantiate handler MenuHandler mh = new MenuHandler(); // Create menu bar JMenuBar mb = new JMenuBar(); // Assemble File menu: JMenu mFile = new JMenu("File"); mFile.setMnemonic('f'); // File | New JMenuItem miFNew = new JMenuItem("New", 'n'); miFNew.addActionListener( mh ); miFNew.setActionCommand("FileNew"); miFNew.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK, true )); mFile.add(miFNew); // File | Open JMenuItem miFOpen = new JMenuItem("Open", 'o'); miFOpen.addActionListener( mh ); miFOpen.setActionCommand("FileOpen"); miFOpen.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK, true )); mFile.add(miFOpen); // File | Save JMenuItem miFSave = new JMenuItem("Save", 's'); miFSave.addActionListener( mh ); miFSave.setActionCommand("FileSave"); miFSave.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK, true )); mFile.add(miFSave); // Separator mFile.addSeparator(); // File | Exit JMenuItem miFExit = new JMenuItem("Exit", 'x'); miFExit.addActionListener( mh ); miFExit.setActionCommand("FileExit"); mFile.add(miFExit); // Attach File menu to menu bar mb.add(mFile);

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xviii

// Create Edit menu from Action objects JMenu mEdit = new JMenu("Edit"); mEdit.setMnemonic('e'); Action actions[] = { actCut, actCopy, actPaste }; int mnemonics[] = { 'c', 'o', 'p' }; for( int i = 0; i < actions.length; i++ ) { JMenuItem mi = mEdit.add(actions[i]); mi.setMnemonic( mnemonics[i]); String s = actions[i].getValue( Action.SHORT_DESCRIPTION ).toString(); mi.setToolTipText( s ); } mb.add(mEdit); // Create Options menu JMenu mOptions = new JMenu("Options"); mOptions.setMnemonic('o'); // Options | Toolbar JMenuItem miOToolbar = new JCheckBoxMenuItem("Toolbar", true); miOToolbar.setMnemonic('t'); miOToolbar.addActionListener( mh ); miOToolbar.setActionCommand("OptionsToolbar"); mOptions.add(miOToolbar); mb.add(mOptions); // Attach menubar to frame. getRootPane().setJMenuBar(mb); } private void showStatus( String text ) { statusBar.showStatus( text ); } // INNER CLASSES // Inner class for status bar private class StatusBar extends JPanel { private JLabel label = new JLabel( " ", JLabel.LEFT ); public StatusBar() { setLayout( new BorderLayout() ); setBackground( Color.lightGray ); label.setForeground( Color.black ); add( label, BorderLayout.SOUTH ); }

}

public void showStatus( String text ) { label.setText( " " + text ); doLayout(); } // end of StatusBar class

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

//

Page xix

// Inner class for toolbar private class ToolBar extends JPanel private class ToolBar extends JToolBar implements ActionListener {

public ToolBar() { // Add actions to the toolbar to create buttons. Action actions[] = { actCut, actCopy, actPaste }; for( int i = 0; i < actions.length; i++ ) { JButton btn = add(actions[i]); String s = actions[i].getValue( Action.SHORT_DESCRIPTION ).toString(); btn.setToolTipText( s ); } /* JButton btnCut = new JButton("Cut"); btnCut.setActionCommand("cut"); btnCut.setMnemonic('c'); btnCut.setToolTipText("Cut to clipboard"); btnCut.addActionListener( this ); JButton btnCopy = new JButton("Copy"); btnCopy.setActionCommand("copy"); btnCopy.setMnemonic('o'); btnCopy.setToolTipText("Copy to clipboard"); btnCopy.addActionListener( this ); JButton btnPaste = new JButton("Paste"); btnPaste.setActionCommand("paste"); btnPaste.setMnemonic('p'); btnPaste.setToolTipText("Paste from clipboard"); btnPaste.addActionListener( this ); setBackground( Color.lightGray ); setLayout( new FlowLayout( FlowLayout.LEFT )); add( btnCut ); add( btnCopy ); add( btnPaste ); */ }

}

// Event handling for Cut, Copy and Paste buttons public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("cut") ) cut(); else if( ae.getActionCommand().equals("copy") ) copy(); else if( ae.getActionCommand().equals("paste") ) paste(); } // end of ToolBar class

// Login window private class LoginDialog extends JDialog implements ActionListener {

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

boolean OKflag[]; JLabel labelUID JLabel labelPWD JTextField tfUID JTextField tfPWD JButton btnOK JButton btnCancel

= = = = = =

new new new new new new

Page xx

JLabel("User ID:", JLabel.RIGHT); JLabel("Password:", JLabel.RIGHT); JTextField(); JTextField(); JButton("OK"); JButton("Cancel");

public LoginDialog( boolean[] OKflagI ) { super( MainWindow.this, "User Login", true ); OKflag = OKflagI; initLayout(); // Set up accelerators & mnemonics // For user ID field, use JTextField.setFocusAccelerator() tfUID.setFocusAccelerator( 'u' ); labelUID.setDisplayedMnemonic( 'u' ); // For password field, use JLabel.setLabelFor() labelPWD.setLabelFor( tfPWD ); labelPWD.setDisplayedMnemonic( 'p' ); // Set up action commands btnOK.setActionCommand("ok"); btnCancel.setActionCommand("cancel"); // Button event handling performed by LoginDialog btnOK.addActionListener( this ); btnCancel.addActionListener( this ); /* // A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { we.getWindow().dispose(); } } ); */ // Use default closing mechanism to close dialog setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); } public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("ok") ) OKflag[0] = true; dispose(); } private void initLayout() {

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxi

GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); getContentPane().setLayout( gbl ); setBounds( 100, 100, 300, 200 ); // Size & position dialog setResizable( false ); // Make dialog fixed size // Add UID label to login window gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelUID, gbc ); // apply constraints getContentPane().add( labelUID ); // Add PWD label to login window gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelPWD, gbc ); // apply constraints getContentPane().add( labelPWD ); // Add UID text field to login window gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfUID, gbc ); // apply constraints getContentPane().add( tfUID ); // Add PWD text field to login window gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfPWD, gbc ); // apply constraints getContentPane().add( tfPWD ); // Add OK button to login window gbc.gridx = 1; gbc.gridy = 2;

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxii

gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnOK, gbc ); // apply constraints getContentPane().add( btnOK ); // Add Cancel button to login window gbc.gridx = 2; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnCancel, gbc ); // apply constraints getContentPane().add( btnCancel ); tfUID.requestFocus(); } }

// Put focus on ID field

// end of initLayout()

// end of LoginWindow class

}

// end of MainWindow class

// // // // //

FontSetter is a convenience class. Its one static method, setFont(), is used to change the font setting for all components in a container. This is simply to make the font bigger for display purposes; it has no bearing on the exercise.

class FontSetter { // Change the font of the desired component and // all its contained components and menus. public static void setFont( Component c, Font f ) { if( c instanceof JMenu ) { JMenu mnu = (JMenu) c; for(int i = 0; i < mnu.getMenuComponentCount(); i++) setFont( mnu.getMenuComponent(i), f ); } else if( c instanceof Container ) { Container cont = (Container) c; for(int i = 0; i < cont.getComponentCount(); i++) setFont( cont.getComponent(i), f ); } c.setFont( f ); } }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxiii

Workshop 5: Using Common Dialogs

SwingApp.java // SwingApp.java // After Dialogs exercise. import import import import import

java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.event.*; javax.swing.text.JTextComponent;

public class SwingApp { public static void main( String[] args ) { new MainWindow(args); } } class MainWindow extends JFrame { private ToolBar toolBar ; private StatusBar statusBar = new StatusBar(); private JTextArea textArea = new JTextArea(); private Action actCut, actCopy, actPaste; // Constructor public MainWindow(String[] args) { super("Studentsoft Super System"); initActions(); initLayout(); initMenu(); // Turn off default closing mechanism setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE ); // A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) {

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxiv

quit(0); } } ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); // Pop login dialog if "login" passed as 1st argument. // If user cancels or closes, close the application. if( args.length > 0 && args[0].toUpperCase().equals("LOGIN") ) if( ! login() ) quit(0); showStatus( "Hello!" ); } // login() pops the LoginDialog, returns true if // user clicks OK, false if user clicks Cancel // or closes. private boolean login() { // return true; boolean bOK[] = new boolean[1]; bOK[0] = false; new LoginDialog(bOK); return bOK[0]; } // Private methods private void cut() { textArea.cut(); showStatus("Text cut to clipboard"); } private void copy() { textArea.copy(); showStatus("Text copied to clipboard"); } private void paste() { textArea.paste(); showStatus("Text pasted from clipboard"); } private boolean quit(int retCode) { int intAnsw = JOptionPane.showConfirmDialog( this, "Are you sure you want to exit?", "Exiting Application", JOptionPane.YES_NO_OPTION ); if( intAnsw == JOptionPane.YES_OPTION ) { System.exit(retCode); return true; } else return false; }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxv

private boolean openFile() { JFileChooser fc = new JFileChooser(); int intAnsw = fc.showOpenDialog(this); // If user clicked cancel, return false if( intAnsw == JFileChooser.CANCEL_OPTION ) return false; showStatus( "Opened file: " + fc.getSelectedFile() ); return true; } private boolean chooseFont( JTextComponent tc ) { // Compose array of font names. String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamily Names(); Font curFont = tc.getFont(); // Get current setting Object oChoice = JOptionPane.showInputDialog( this, "Choose a font:", "Choose Font", JOptionPane.QUESTION_MESSAGE, null, fonts, curFont.getName() ); if( oChoice == null ) return false; tc.setFont( new Font( (String) oChoice, curFont.getStyle(), curFont.getSize() )); tc.repaint(); return true; } // Set up Action objects private void initActions() { // Action objects for cut, copy, paste: actCut = new AbstractAction("Cut") { public void actionPerformed(ActionEvent ae) { cut(); } }; actCut.putValue(Action.SHORT_DESCRIPTION, "Cut text to clipboard"); actCopy = new AbstractAction("Copy") { public void actionPerformed(ActionEvent ae) { copy(); } }; actCopy.putValue(Action.SHORT_DESCRIPTION, "Copy text to clipboard"); actPaste = new AbstractAction("Paste") { public void actionPerformed(ActionEvent ae) { paste(); } }; actPaste.putValue(Action.SHORT_DESCRIPTION,

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxvi

"Paste text from clipboard"); } private void initLayout() { toolBar = new ToolBar(); // Configure text area textArea.setLineWrap( true ); textArea.setWrapStyleWord( true ); textArea.setToolTipText("Enter / edit text here"); // Configure frame setBounds( 100, 100, 500, 300 ); getContentPane().add( BorderLayout.NORTH , getContentPane().add( BorderLayout.CENTER, getContentPane().add( BorderLayout.SOUTH ,

toolBar ); textArea ); statusBar );

// Create caret listener for textArea to react when // selection changes textArea.addCaretListener( new CaretListener() { public void caretUpdate(CaretEvent e) { boolean isSelection = textArea.getSelectionStart() != textArea.getSelectionEnd(); actCut.setEnabled(isSelection); actCopy.setEnabled(isSelection); } }); } private void initMenu() { // Local inner class for handling menu items class MenuHandler implements ActionListener { public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("FileNew") ) showStatus("New file created"); else if( ae.getActionCommand().equals("FileOpen") ) // showStatus("File opened"); openFile(); else if( ae.getActionCommand().equals("FileSave") ) showStatus("File saved"); else if( ae.getActionCommand().equals("FileExit") ) quit( 0 ); // Toggle toolbar visibility else if( ae.getActionCommand().equals("OptionsToolbar") ) { // Get source, cast it as JCheckBoxMenuItem: JCheckBoxMenuItem cbmi = (JCheckBoxMenuItem) ae.getSource(); toolBar.setVisible( cbmi.isSelected() ); getContentPane().doLayout(); } // Set font on text area else if( ae.getActionCommand().equals("OptionsFont") ) chooseFont(textArea);

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxvii

} } // Instantiate handler MenuHandler mh = new MenuHandler(); // Create menu bar JMenuBar mb = new JMenuBar(); // Assemble File menu: JMenu mFile = new JMenu("File"); mFile.setMnemonic('f'); // File | New JMenuItem miFNew = new JMenuItem("New", 'n'); miFNew.addActionListener( mh ); miFNew.setActionCommand("FileNew"); miFNew.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK, true )); mFile.add(miFNew); // File | Open JMenuItem miFOpen = new JMenuItem("Open", 'o'); miFOpen.addActionListener( mh ); miFOpen.setActionCommand("FileOpen"); miFOpen.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK, true )); mFile.add(miFOpen); // File | Save JMenuItem miFSave = new JMenuItem("Save", 's'); miFSave.addActionListener( mh ); miFSave.setActionCommand("FileSave"); miFSave.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK, true )); mFile.add(miFSave); // Separator mFile.addSeparator(); // File | Exit JMenuItem miFExit = new JMenuItem("Exit", 'x'); miFExit.addActionListener( mh ); miFExit.setActionCommand("FileExit"); mFile.add(miFExit); // Attach File menu to menu bar mb.add(mFile); // Create Edit menu from Action objects JMenu mEdit = new JMenu("Edit"); mEdit.setMnemonic('e'); Action actions[] = { actCut, actCopy, actPaste }; int mnemonics[] = { 'c', 'o', 'p' }; for( int i = 0; i < actions.length; i++ ) { JMenuItem mi = mEdit.add(actions[i]);

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxviii

mi.setMnemonic( mnemonics[i]); String s = actions[i].getValue( Action.SHORT_DESCRIPTION ).toString(); mi.setToolTipText( s ); } mb.add(mEdit); // Create Options menu JMenu mOptions = new JMenu("Options"); mOptions.setMnemonic('o'); // Options | Toolbar JMenuItem miOToolbar = new JCheckBoxMenuItem("Toolbar", true); miOToolbar.setMnemonic('t'); miOToolbar.addActionListener( mh ); miOToolbar.setActionCommand("OptionsToolbar"); mOptions.add(miOToolbar); // Add separator & Font item to Options menu mOptions.addSeparator(); JMenuItem miOFont = new JMenuItem("Text Font...", 'f'); miOFont.addActionListener( mh ); miOFont.setActionCommand("OptionsFont"); mOptions.add(miOFont); mb.add(mOptions); // Attach menubar to frame. getRootPane().setJMenuBar(mb); } private void showStatus( String text ) { statusBar.showStatus( text ); } // INNER CLASSES // Inner class for status bar private class StatusBar extends JPanel { private JLabel label_ = new JLabel( " ", JLabel.LEFT ); public StatusBar() { setLayout( new BorderLayout() ); setBackground( Color.lightGray ); label_.setForeground( Color.black ); add( label_, BorderLayout.SOUTH ); }

} //

public void showStatus( String text ) { label_.setText( " " + text ); doLayout(); } // end of StatusBar class

// Inner class for toolbar private class ToolBar extends JPanel

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxix

private class ToolBar extends JToolBar implements ActionListener { public ToolBar() { // Add actions to the toolbar to create buttons. Action actions[] = { actCut, actCopy, actPaste }; for( int i = 0; i < actions.length; i++ ) { JButton btn = add(actions[i]); String s = actions[i].getValue( Action.SHORT_DESCRIPTION ).toString(); btn.setToolTipText( s ); } /* JButton btnCut = new JButton("Cut"); btnCut.setActionCommand("cut"); btnCut.setMnemonic('c'); btnCut.setToolTipText("Cut to clipboard"); btnCut.addActionListener( this ); JButton btnCopy = new JButton("Copy"); btnCopy.setActionCommand("copy"); btnCopy.setMnemonic('o'); btnCopy.setToolTipText("Copy to clipboard"); btnCopy.addActionListener( this ); JButton btnPaste = new JButton("Paste"); btnPaste.setActionCommand("paste"); btnPaste.setMnemonic('p'); btnPaste.setToolTipText("Paste from clipboard"); btnPaste.addActionListener( this ); setBackground( Color.lightGray ); setLayout( new FlowLayout( FlowLayout.LEFT )); add( btnCut ); add( btnCopy ); add( btnPaste ); */ }

}

// Event handling for Cut, Copy and Paste buttons public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("cut") ) cut(); else if( ae.getActionCommand().equals("copy") ) copy(); else if( ae.getActionCommand().equals("paste") ) paste(); } // end of ToolBar class

// Login window private class LoginDialog extends JDialog implements ActionListener { boolean OKflag[];

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

JLabel labelUID JLabel labelPWD JTextField tfUID JTextField tfPWD JButton btnOK JButton btnCancel

= = = = = =

new new new new new new

Page xxx

JLabel("User ID:", JLabel.RIGHT); JLabel("Password:", JLabel.RIGHT); JTextField(); JTextField(); JButton("OK"); JButton("Cancel");

public LoginDialog( boolean[] OKflagI ) { super( MainWindow.this, "User Login", true ); OKflag = OKflagI; initLayout(); // Set up accelerators & mnemonics // For user ID field, use JTextField.setFocusAccelerator() tfUID.setFocusAccelerator( 'u' ); labelUID.setDisplayedMnemonic( 'u' ); // For password field, use JLabel.setLabelFor() labelPWD.setLabelFor( tfPWD ); labelPWD.setDisplayedMnemonic( 'p' ); // Set up action commands btnOK.setActionCommand("ok"); btnCancel.setActionCommand("cancel"); // Button event handling performed by LoginDialog btnOK.addActionListener( this ); btnCancel.addActionListener( this ); /* // A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { we.getWindow().dispose(); } } ); */ // Use default closing mechanism to close dialog setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); } public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("ok") ) { // Check if User ID is correct if( ! tfUID.getText().trim().toUpperCase().equals("STUDENT") ) { JOptionPane.showMessageDialog( null, "Sorry, invalid user ID.\nTry again.", "Invalid Login", JOptionPane.WARNING_MESSAGE ); tfUID.requestFocus();

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxxi

tfUID.selectAll(); return; } // Check if password is correct if( ! tfPWD.getText().trim().toUpperCase().equals("LEARN") ) { JOptionPane.showMessageDialog( null, "Sorry, invalid password.\nTry again.", "Invalid Login", JOptionPane.WARNING_MESSAGE ); tfPWD.requestFocus(); tfPWD.selectAll(); return; } OKflag[0] = true; } dispose(); } private void initLayout() { GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); getContentPane().setLayout( gbl ); setBounds( 100, 100, 300, 200 ); // Size & position dialog setResizable( false ); // Make dialog fixed size // Add UID label to login window gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelUID, gbc ); // apply constraints getContentPane().add( labelUID ); // Add PWD label to login window gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelPWD, gbc ); // apply constraints getContentPane().add( labelPWD ); // Add UID text field to login window gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1;

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxxii

gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfUID, gbc ); // apply constraints getContentPane().add( tfUID ); // Add PWD text field to login window gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfPWD, gbc ); // apply constraints getContentPane().add( tfPWD ); // Add OK button to login window gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnOK, gbc ); // apply constraints getContentPane().add( btnOK ); // Add Cancel button to login window gbc.gridx = 2; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnCancel, gbc ); // apply constraints getContentPane().add( btnCancel ); tfUID.requestFocus(); } }

// Put focus on ID field

// end of initLayout()

// end of LoginWindow class

}

// end of MainWindow class

// // // // //

FontSetter is a convenience class. Its one static method, setFont(), is used to change the font setting for all components in a container. This is simply to make the font bigger for display purposes; it has no bearing on the exercise.

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxxiii

class FontSetter { // Change the font of the desired component and // all its contained components and menus. public static void setFont( Component c, Font f ) { if( c instanceof JMenu ) { JMenu mnu = (JMenu) c; for(int i = 0; i < mnu.getMenuComponentCount(); i++) setFont( mnu.getMenuComponent(i), f ); } else if( c instanceof Container ) { Container cont = (Container) c; for(int i = 0; i < cont.getComponentCount(); i++) setFont( cont.getComponent(i), f ); } c.setFont( f ); } }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxxiv

Workshop 6: Using Borders

SwingApp.java // SwingApp.java // After Borders exercise. import import import import import import

java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.border.*; javax.swing.event.*; javax.swing.text.JTextComponent;

public class SwingApp { public static void main( String[] args ) { new MainWindow(args); } } class MainWindow extends JFrame { private ToolBar toolBar ; private StatusBar statusBar = new StatusBar(); private JTextArea textArea = new JTextArea(); private Action actCut, actCopy, actPaste; // Constructor public MainWindow(String[] args) { super("Studentsoft Super System"); initActions(); initLayout(); initMenu(); // Turn off default closing mechanism setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE ); // A simple anonymous adapter to handle // windowClosing event.

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxxv

addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { quit(0); } } ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); // Pop login dialog if "login" passed as 1st argument. // If user cancels or closes, close the application. if( args.length > 0 && args[0].toUpperCase().equals("LOGIN") ) if( ! login() ) quit(0); showStatus( "Hello!" ); } // login() pops the LoginDialog, returns true if // user clicks OK, false if user clicks Cancel // or closes. private boolean login() { // return true; boolean bOK[] = new boolean[1]; bOK[0] = false; new LoginDialog(bOK); return bOK[0]; } // Private methods private void cut() { textArea.cut(); showStatus("Text cut to clipboard"); } private void copy() { textArea.copy(); showStatus("Text copied to clipboard"); } private void paste() { textArea.paste(); showStatus("Text pasted from clipboard"); } private boolean quit(int retCode) { int intAnsw = JOptionPane.showConfirmDialog( this, "Are you sure you want to exit?", "Exiting Application", JOptionPane.YES_NO_OPTION ); if( intAnsw == JOptionPane.YES_OPTION ) { System.exit(retCode); return true; } else return false; }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxxvi

private boolean openFile() { JFileChooser fc = new JFileChooser(); int intAnsw = fc.showOpenDialog(this); // If user clicked cancel, return false if( intAnsw == JFileChooser.CANCEL_OPTION ) return false; showStatus( "Opened file: " + fc.getSelectedFile() ); return true; } private boolean chooseFont( JTextComponent tc ) { // Compose array of font names. String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamily Names(); Font curFont = tc.getFont(); // Get current setting Object oChoice = JOptionPane.showInputDialog( this, "Choose a font:", "Choose Font", JOptionPane.QUESTION_MESSAGE, null, fonts, curFont.getName() ); if( oChoice == null ) return false; tc.setFont( new Font( (String) oChoice, curFont.getStyle(), curFont.getSize() )); tc.repaint(); return true; } // Set up Action objects private void initActions() { // Action objects for cut, copy, paste: actCut = new AbstractAction("Cut") { public void actionPerformed(ActionEvent ae) { cut(); } }; actCut.putValue(Action.SHORT_DESCRIPTION, "Cut text to clipboard"); actCopy = new AbstractAction("Copy") { public void actionPerformed(ActionEvent ae) { copy(); } }; actCopy.putValue(Action.SHORT_DESCRIPTION, "Copy text to clipboard"); actPaste = new AbstractAction("Paste") { public void actionPerformed(ActionEvent ae) { paste(); }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxxvii

}; actPaste.putValue(Action.SHORT_DESCRIPTION, "Paste text from clipboard"); } private void initLayout() { toolBar = new ToolBar(); // Configure text area textArea.setLineWrap( true ); textArea.setWrapStyleWord( true ); textArea.setToolTipText("Enter / edit text here"); textArea.setBorder( BorderFactory.createTitledBorder( "Workspace" )); // Configure frame setBounds( 100, 100, 500, 300 ); getContentPane().add( BorderLayout.NORTH , getContentPane().add( BorderLayout.CENTER, getContentPane().add( BorderLayout.SOUTH ,

toolBar ); textArea ); statusBar );

// Create caret listener for textArea to react when // selection changes textArea.addCaretListener( new CaretListener() { public void caretUpdate(CaretEvent e) { boolean isSelection = textArea.getSelectionStart() != textArea.getSelectionEnd(); actCut.setEnabled(isSelection); actCopy.setEnabled(isSelection); } }); } private void initMenu() { // Local inner class for handling menu items class MenuHandler implements ActionListener { public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("FileNew") ) showStatus("New file created"); else if( ae.getActionCommand().equals("FileOpen") ) // showStatus("File opened"); openFile(); else if( ae.getActionCommand().equals("FileSave") ) showStatus("File saved"); else if( ae.getActionCommand().equals("FileExit") ) quit( 0 ); // Toggle toolbar visibility else if( ae.getActionCommand().equals("OptionsToolbar") ) { // Get source, cast it as JCheckBoxMenuItem: JCheckBoxMenuItem cbmi = (JCheckBoxMenuItem) ae.getSource(); toolBar.setVisible( cbmi.isSelected() ); getContentPane().doLayout(); }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxxviii

// Set font on text area else if( ae.getActionCommand().equals("OptionsFont") ) chooseFont(textArea); } } // Instantiate handler MenuHandler mh = new MenuHandler(); // Create menu bar JMenuBar mb = new JMenuBar(); // Assemble File menu: JMenu mFile = new JMenu("File"); mFile.setMnemonic('f'); // File | New JMenuItem miFNew = new JMenuItem("New", 'n'); miFNew.addActionListener( mh ); miFNew.setActionCommand("FileNew"); miFNew.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK, true )); mFile.add(miFNew); // File | Open JMenuItem miFOpen = new JMenuItem("Open", 'o'); miFOpen.addActionListener( mh ); miFOpen.setActionCommand("FileOpen"); miFOpen.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK, true )); mFile.add(miFOpen); // File | Save JMenuItem miFSave = new JMenuItem("Save", 's'); miFSave.addActionListener( mh ); miFSave.setActionCommand("FileSave"); miFSave.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK, true )); mFile.add(miFSave); // Separator mFile.addSeparator(); // File | Exit JMenuItem miFExit = new JMenuItem("Exit", 'x'); miFExit.addActionListener( mh ); miFExit.setActionCommand("FileExit"); mFile.add(miFExit); // Attach File menu to menu bar mb.add(mFile); // Create Edit menu from Action objects JMenu mEdit = new JMenu("Edit"); mEdit.setMnemonic('e');

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xxxix

Action actions[] = { actCut, actCopy, actPaste }; int mnemonics[] = { 'c', 'o', 'p' }; for( int i = 0; i < actions.length; i++ ) { JMenuItem mi = mEdit.add(actions[i]); mi.setMnemonic( mnemonics[i]); String s = actions[i].getValue( Action.SHORT_DESCRIPTION ).toString(); mi.setToolTipText( s ); } mb.add(mEdit); // Create Options menu JMenu mOptions = new JMenu("Options"); mOptions.setMnemonic('o'); // Options | Toolbar JMenuItem miOToolbar = new JCheckBoxMenuItem("Toolbar", true); miOToolbar.setMnemonic('t'); miOToolbar.addActionListener( mh ); miOToolbar.setActionCommand("OptionsToolbar"); mOptions.add(miOToolbar); // Add separator & Font item to Options menu mOptions.addSeparator(); JMenuItem miOFont = new JMenuItem("Text Font...", 'f'); miOFont.addActionListener( mh ); miOFont.setActionCommand("OptionsFont"); mOptions.add(miOFont); mb.add(mOptions); // Attach menubar to frame. getRootPane().setJMenuBar(mb); } private void showStatus( String text ) { statusBar.showStatus( text ); } // INNER CLASSES // Inner class for status bar private class StatusBar extends JPanel { private JLabel label = new JLabel( "", JLabel.LEFT ); public StatusBar() { setLayout( new BorderLayout() ); setBackground( Color.lightGray ); label.setForeground( Color.black ); label.setBorder( BorderFactory.createLoweredBevelBorder()); add( label, BorderLayout.SOUTH ); } public void showStatus( String text ) { label.setText( " " + text ); doLayout();

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

} //

Page xl

} // end of StatusBar class

// Inner class for toolbar private class ToolBar extends JPanel private class ToolBar extends JToolBar implements ActionListener {

public ToolBar() { // Add actions to the toolbar to create buttons. Action actions[] = { actCut, actCopy, actPaste }; for( int i = 0; i < actions.length; i++ ) { JButton btn = add(actions[i]); String s = actions[i].getValue( Action.SHORT_DESCRIPTION ).toString(); btn.setToolTipText( s ); } /* JButton btnCut = new JButton("Cut"); btnCut.setActionCommand("cut"); btnCut.setMnemonic('c'); btnCut.setToolTipText("Cut to clipboard"); btnCut.addActionListener( this ); JButton btnCopy = new JButton("Copy"); btnCopy.setActionCommand("copy"); btnCopy.setMnemonic('o'); btnCopy.setToolTipText("Copy to clipboard"); btnCopy.addActionListener( this ); JButton btnPaste = new JButton("Paste"); btnPaste.setActionCommand("paste"); btnPaste.setMnemonic('p'); btnPaste.setToolTipText("Paste from clipboard"); btnPaste.addActionListener( this ); setBackground( Color.lightGray ); setLayout( new FlowLayout( FlowLayout.LEFT )); add( btnCut ); add( btnCopy ); add( btnPaste ); */ }

}

// Event handling for Cut, Copy and Paste buttons public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("cut") ) cut(); else if( ae.getActionCommand().equals("copy") ) copy(); else if( ae.getActionCommand().equals("paste") ) paste(); } // end of ToolBar class

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xli

// Login window private class LoginDialog extends JDialog implements ActionListener { boolean OKflag[]; JLabel labelUID JLabel labelPWD JTextField tfUID JTextField tfPWD JButton btnOK JButton btnCancel

= = = = = =

new new new new new new

JLabel("User ID:", JLabel.RIGHT); JLabel("Password:", JLabel.RIGHT); JTextField(); JTextField(); JButton("OK"); JButton("Cancel");

public LoginDialog( boolean[] OKflagI ) { super( MainWindow.this, "User Login", true ); OKflag = OKflagI; initLayout(); // Set up accelerators & mnemonics // For user ID field, use JTextField.setFocusAccelerator() tfUID.setFocusAccelerator( 'u' ); labelUID.setDisplayedMnemonic( 'u' ); // For password field, use JLabel.setLabelFor() labelPWD.setLabelFor( tfPWD ); labelPWD.setDisplayedMnemonic( 'p' ); // Set up action commands btnOK.setActionCommand("ok"); btnCancel.setActionCommand("cancel"); // Button event handling performed by LoginDialog btnOK.addActionListener( this ); btnCancel.addActionListener( this ); /* // A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { we.getWindow().dispose(); } } ); */ // Use default closing mechanism to close dialog setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); } public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("ok") ) { // Check if User ID is correct

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xlii

if( ! tfUID.getText().trim().toUpperCase().equals("STUDENT") ) { JOptionPane.showMessageDialog( null, "Sorry, invalid user ID.\nTry again.", "Invalid Login", JOptionPane.WARNING_MESSAGE ); tfUID.requestFocus(); tfUID.selectAll(); return; } // Check if password is correct if( ! tfPWD.getText().trim().toUpperCase().equals("LEARN") ) { JOptionPane.showMessageDialog( null, "Sorry, invalid password.\nTry again.", "Invalid Login", JOptionPane.WARNING_MESSAGE ); tfPWD.requestFocus(); tfPWD.selectAll(); return; } OKflag[0] = true; } dispose(); } private void initLayout() { GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); getContentPane().setLayout( gbl ); setBounds( 100, 100, 300, 200 ); // Size & position dialog setResizable( false ); // Make dialog fixed size // Add UID label to login window gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelUID, gbc ); // apply constraints getContentPane().add( labelUID ); // Add PWD label to login window gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelPWD, gbc ); // apply constraints getContentPane().add( labelPWD );

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xliii

// Add UID text field to login window gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfUID, gbc ); // apply constraints getContentPane().add( tfUID ); // Add PWD text field to login window gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfPWD, gbc ); // apply constraints getContentPane().add( tfPWD ); // Add OK button to login window gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnOK, gbc ); // apply constraints getContentPane().add( btnOK ); // Add Cancel button to login window gbc.gridx = 2; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnCancel, gbc ); // apply constraints getContentPane().add( btnCancel ); tfUID.requestFocus(); } } }

// Put focus on ID field

// end of initLayout()

// end of LoginWindow class

// end of MainWindow class

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

// // // // //

Page xliv

FontSetter is a convenience class. Its one static method, setFont(), is used to change the font setting for all components in a container. This is simply to make the font bigger for display purposes; it has no bearing on the exercise.

class FontSetter { // Change the font of the desired component and // all its contained components and menus. public static void setFont( Component c, Font f ) { if( c instanceof JMenu ) { JMenu mnu = (JMenu) c; for(int i = 0; i < mnu.getMenuComponentCount(); i++) setFont( mnu.getMenuComponent(i), f ); } else if( c instanceof Container ) { Container cont = (Container) c; for(int i = 0; i < cont.getComponentCount(); i++) setFont( cont.getComponent(i), f ); } c.setFont( f ); } }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xlv

Workshop 7: Using Internal Frames

SwingApp.java // SwingApp.java // After Internal Frames exercise. import import import import import import

java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.border.*; javax.swing.event.*; javax.swing.text.JTextComponent;

public class SwingApp { public static void main( String[] args ) { new MainWindow(args); } } class MainWindow extends JFrame { private ToolBar toolBar_ ; private StatusBar statusBar_ = new StatusBar(); private JTextArea textArea_; // = new JTextArea(); private Action actCut_, actCopy_, actPaste_; private JDesktopPane desktop_ = new JDesktopPane(); private int intNewFileCounter; // Constructor public MainWindow(String[] args) { super("Studentsoft Super System"); initActions(); initLayout(); initMenu(); // Turn off default closing mechanism setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE );

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xlvi

// A simple anonymous adapter to handle // windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { quit(0); } } ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); // Pop login dialog if "login" passed as 1st argument. // If user cancels or closes, close the application. if( args.length > 0 && args[0].toUpperCase().equals("LOGIN") ) if( ! login() ) quit(0); showStatus( "Hello!" ); } // login() pops the LoginDialog, returns true if // user clicks OK, false if user clicks Cancel // or closes. private boolean login() { // return true; boolean bOK[] = new boolean[1]; bOK[0] = false; new LoginDialog(bOK); return bOK[0]; } // Private methods private void cut() { textArea_.cut(); showStatus("Text cut to clipboard"); } private void copy() { textArea_.copy(); showStatus("Text copied to clipboard"); } private void paste() { textArea_.paste(); showStatus("Text pasted from clipboard"); } private boolean quit(int retCode) { int intAnsw = JOptionPane.showConfirmDialog( this, "Are you sure you want to exit?", "Exiting Application", JOptionPane.YES_NO_OPTION ); if( intAnsw == JOptionPane.YES_OPTION ) { System.exit(retCode); return true; } else

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xlvii

return false; } private void newChild( String title ) { JInternalFrame pad = new NotepadChild( title ); desktop_.add( pad ); try { pad.setSelected(true); // Make it the active notepad } catch( Exception e ) {} } private void newFile() { newChild( "Untitled " + }

++intNewFileCounter );

private boolean openFile() { JFileChooser fc = new JFileChooser(); int intAnsw = fc.showOpenDialog(this); // If user clicked cancel, return false if( intAnsw == JFileChooser.CANCEL_OPTION ) return false; newChild( fc.getSelectedFile().toString() ); showStatus( "Opened file: " + fc.getSelectedFile() ); return true; } private boolean chooseFont( JTextComponent tc ) { // Compose array of font names. String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamily Names(); Font curFont = tc.getFont(); // Get current setting Object oChoice = JOptionPane.showInputDialog( this, "Choose a font:", "Choose Font", JOptionPane.QUESTION_MESSAGE, null, fonts, curFont.getName() ); if( oChoice == null ) return false; tc.setFont( new Font( (String) oChoice, curFont.getStyle(), curFont.getSize() )); tc.repaint(); return true; } // Set up Action objects private void initActions() { // Action objects for cut, copy, paste: actCut_ = new AbstractAction("Cut") { public void actionPerformed(ActionEvent ae) { cut(); } };

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xlviii

actCut_.putValue(Action.SHORT_DESCRIPTION, "Cut text to clipboard"); actCopy_ = new AbstractAction("Copy") { public void actionPerformed(ActionEvent ae) { copy(); } }; actCopy_.putValue(Action.SHORT_DESCRIPTION, "Copy text to clipboard"); actPaste_ = new AbstractAction("Paste") { public void actionPerformed(ActionEvent ae) { paste(); } }; actPaste_.putValue(Action.SHORT_DESCRIPTION, "Paste text from clipboard"); } private void initLayout() { toolBar_ = new ToolBar(); /* // Configure text area textArea_.setLineWrap( true ); textArea_.setWrapStyleWord( true ); textArea_.setToolTipText("Enter / edit text here"); textArea_.setBorder( BorderFactory.createTitledBorder( "Workspace" )); */ // Configure frame setBounds( 100, 100, 500, 300 ); getContentPane().add( BorderLayout.NORTH , toolBar_ ); getContentPane().add( BorderLayout.CENTER, textArea_ ); getContentPane().add( BorderLayout.CENTER, desktop_ ); getContentPane().add( BorderLayout.SOUTH , statusBar_ );

//

/* // Create caret listener for textArea_ to react when // selection changes textArea_.addCaretListener( new CaretListener() { public void caretUpdate(CaretEvent e) { boolean isSelection = textArea_.getSelectionStart() != textArea_.getSelectionEnd(); actCut_.setEnabled(isSelection); actCopy_.setEnabled(isSelection); } }); */ } private void initMenu() { // Local inner class for handling menu items class MenuHandler implements ActionListener { public void actionPerformed( ActionEvent ae ) {

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page xlix

if( ae.getActionCommand().equals("FileNew") ) { newFile(); showStatus("New file created"); } else if( ae.getActionCommand().equals("FileOpen") ) // showStatus("File opened"); openFile(); else if( ae.getActionCommand().equals("FileSave") ) showStatus("File saved"); else if( ae.getActionCommand().equals("FileExit") ) quit( 0 ); // Toggle toolbar visibility else if( ae.getActionCommand().equals("OptionsToolbar") ) { // Get source, cast it as JCheckBoxMenuItem: JCheckBoxMenuItem cbmi = (JCheckBoxMenuItem) ae.getSource(); toolBar_.setVisible( cbmi.isSelected() ); getContentPane().doLayout(); } // Set font on text area else if( ae.getActionCommand().equals("OptionsFont") ) chooseFont(textArea_); } } // Instantiate handler MenuHandler mh = new MenuHandler(); // Create menu bar JMenuBar mb = new JMenuBar(); // Assemble File menu: JMenu mFile = new JMenu("File"); mFile.setMnemonic('f'); // File | New JMenuItem miFNew = new JMenuItem("New", 'n'); miFNew.addActionListener( mh ); miFNew.setActionCommand("FileNew"); miFNew.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK, true )); mFile.add(miFNew); // File | Open JMenuItem miFOpen = new JMenuItem("Open", 'o'); miFOpen.addActionListener( mh ); miFOpen.setActionCommand("FileOpen"); miFOpen.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK, true )); mFile.add(miFOpen); // File | Save JMenuItem miFSave = new JMenuItem("Save", 's'); miFSave.addActionListener( mh ); miFSave.setActionCommand("FileSave");

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page l

miFSave.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK, true )); mFile.add(miFSave); // Separator mFile.addSeparator(); // File | Exit JMenuItem miFExit = new JMenuItem("Exit", 'x'); miFExit.addActionListener( mh ); miFExit.setActionCommand("FileExit"); mFile.add(miFExit); // Attach File menu to menu bar mb.add(mFile); // Create Edit menu from Action objects JMenu mEdit = new JMenu("Edit"); mEdit.setMnemonic('e'); Action actions[] = { actCut_, actCopy_, actPaste_ }; int mnemonics[] = { 'c', 'o', 'p' }; for( int i = 0; i < actions.length; i++ ) { JMenuItem mi = mEdit.add(actions[i]); mi.setMnemonic( mnemonics[i]); String s = actions[i].getValue( Action.SHORT_DESCRIPTION ).toString(); mi.setToolTipText( s ); } mb.add(mEdit); // Create Options menu JMenu mOptions = new JMenu("Options"); mOptions.setMnemonic('o'); // Options | Toolbar JMenuItem miOToolbar = new JCheckBoxMenuItem("Toolbar", true); miOToolbar.setMnemonic('t'); miOToolbar.addActionListener( mh ); miOToolbar.setActionCommand("OptionsToolbar"); mOptions.add(miOToolbar); // Add separator & Font item to Options menu mOptions.addSeparator(); JMenuItem miOFont = new JMenuItem("Text Font...", 'f'); miOFont.addActionListener( mh ); miOFont.setActionCommand("OptionsFont"); mOptions.add(miOFont); mb.add(mOptions); // Attach menubar to frame. getRootPane().setJMenuBar(mb);

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page li

} private void showStatus( String text ) { statusBar_.showStatus( text ); } // INNER CLASSES // Inner class for status bar private class StatusBar extends JPanel { private JLabel label_ = new JLabel( "", JLabel.LEFT ); public StatusBar() { setLayout( new BorderLayout() ); setBackground( Color.lightGray ); label_.setForeground( Color.black ); label_.setBorder( BorderFactory.createLoweredBevelBorder()); add( label_, BorderLayout.SOUTH ); }

} //

public void showStatus( String text ) { label_.setText( " " + text ); doLayout(); } // end of StatusBar class

// Inner class for toolbar private class ToolBar extends JPanel private class ToolBar extends JToolBar implements ActionListener {

public ToolBar() { // Add actions to the toolbar to create buttons. Action actions[] = { actCut_, actCopy_, actPaste_ }; for( int i = 0; i < actions.length; i++ ) { JButton btn = add(actions[i]); String s = actions[i].getValue( Action.SHORT_DESCRIPTION ).toString(); btn.setToolTipText( s ); } /* JButton btnCut = new JButton("Cut"); btnCut.setActionCommand("cut"); btnCut.setMnemonic('c'); btnCut.setToolTipText("Cut to clipboard"); btnCut.addActionListener( this ); JButton btnCopy = new JButton("Copy"); btnCopy.setActionCommand("copy"); btnCopy.setMnemonic('o'); btnCopy.setToolTipText("Copy to clipboard"); btnCopy.addActionListener( this ); JButton btnPaste = new JButton("Paste"); btnPaste.setActionCommand("paste"); btnPaste.setMnemonic('p'); btnPaste.setToolTipText("Paste from clipboard"); btnPaste.addActionListener( this );

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page lii

setBackground( Color.lightGray ); setLayout( new FlowLayout( FlowLayout.LEFT )); add( btnCut ); add( btnCopy ); add( btnPaste ); */ }

}

// Event handling for Cut, Copy and Paste buttons public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("cut") ) cut(); else if( ae.getActionCommand().equals("copy") ) copy(); else if( ae.getActionCommand().equals("paste") ) paste(); } // end of ToolBar class

// Login window private class LoginDialog extends JDialog implements ActionListener { boolean OKflag_[]; JLabel labelUID_ JLabel labelPWD_ JTextField tfUID_ JTextField tfPWD_ JButton btnOK_ JButton btnCancel_

= = = = = =

new new new new new new

JLabel("User ID:", JLabel.RIGHT); JLabel("Password:", JLabel.RIGHT); JTextField(); JTextField(); JButton("OK"); JButton("Cancel");

public LoginDialog( boolean[] OKflag ) { super( MainWindow.this, "User Login", true ); OKflag_ = OKflag; initLayout(); // Set up accelerators & mnemonics // For user ID field, use JTextField.setFocusAccelerator() tfUID_.setFocusAccelerator( 'u' ); labelUID_.setDisplayedMnemonic( 'u' ); // For password field, use JLabel.setLabelFor() labelPWD_.setLabelFor( tfPWD_ ); labelPWD_.setDisplayedMnemonic( 'p' ); // Set up action commands btnOK_.setActionCommand("ok"); btnCancel_.setActionCommand("cancel"); // Button event handling performed by LoginDialog btnOK_.addActionListener( this ); btnCancel_.addActionListener( this ); /* // A simple anonymous adapter to handle

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page liii

// windowClosing event. addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we ) { we.getWindow().dispose(); } } ); */ // Use default closing mechanism to close dialog setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE ); // Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); show(); } public void actionPerformed( ActionEvent ae ) { if( ae.getActionCommand().equals("ok") ) { // Check if User ID is correct if( ! tfUID_.getText().trim().toUpperCase().equals("ALICE") ) { JOptionPane.showMessageDialog( null, "Sorry, invalid user ID.\nTry again.", "Invalid Login", JOptionPane.WARNING_MESSAGE ); tfUID_.requestFocus(); tfUID_.selectAll(); return; } // Check if password is correct if( ! tfPWD_.getText().trim().toUpperCase().equals("DRINK ME") ) { JOptionPane.showMessageDialog( null, "Sorry, invalid password.\nTry again.", "Invalid Login", JOptionPane.WARNING_MESSAGE ); tfPWD_.requestFocus(); tfPWD_.selectAll(); return; } OKflag_[0] = true; } dispose(); } private void initLayout() { GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); getContentPane().setLayout( gbl ); setBounds( 100, 100, 300, 200 ); // Size & position dialog setResizable( false ); // Make dialog fixed size // Add UID label gbc.gridx = gbc.gridy = gbc.gridwidth =

© 2003 SkillBuilders Inc.

to login window 0; 0; 2;

V 2.1

Java SWing: Workshop Solutions

Page liv

gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelUID_, gbc ); // apply constraints getContentPane().add( labelUID_ ); // Add PWD label to login window gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( labelPWD_, gbc ); // apply constraints getContentPane().add( labelPWD_ ); // Add UID text field to login window gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfUID_, gbc ); // apply constraints getContentPane().add( tfUID_ ); // Add PWD text field to login window gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbl.setConstraints( tfPWD_, gbc ); // apply constraints getContentPane().add( tfPWD_ ); // Add OK button to login window gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 0; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnOK_, gbc ); // apply constraints getContentPane().add( btnOK_ ); // Add Cancel button to login window gbc.gridx = 2;

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page lv

gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbl.setConstraints( btnCancel_, gbc ); // apply constraints getContentPane().add( btnCancel_ ); tfUID_.requestFocus(); } }

// Put focus on ID field

// end of initLayout()

// end of LoginWindow class

// NotepadChild class is the internal frame private class NotepadChild extends JInternalFrame { private JTextArea textArea_ = new JTextArea(); public NotepadChild( String title ) { super( title, true, true, true, true ); // Configure text area textArea_.setLineWrap( true ); textArea_.setWrapStyleWord( true ); textArea_.setToolTipText("Enter / edit text here"); getContentPane().add( BorderLayout.CENTER, textArea_ ); FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 24) ); pack(); setBounds( 50, 50, 300, 150 ); // Register a simple adapter to handle when internal frame // becomes active. addInternalFrameListener( new InternalFrameAdapter(){ public void internalFrameActivated(InternalFrameEvent e) { // Assign my text area as the one referenced by MainWindow MainWindow.this.textArea_ = textArea_; } }); // Create caret listener for textArea_ to react when // selection changes textArea_.addCaretListener( new CaretListener() { public void caretUpdate(CaretEvent e) { boolean isSelection = textArea_.getSelectionStart() != textArea_.getSelectionEnd(); actCut_.setEnabled(isSelection); actCopy_.setEnabled(isSelection); } }); }

// end of NotepadChild ctor

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

}

Page lvi

// end of NotepadChild class

}

// end of MainWindow class

// // // // //

FontSetter is a convenience class. Its one static method, setFont(), is used to change the font setting for all components in a container. This is simply to make the font bigger for display purposes; it has no bearing on the exercise.

class FontSetter { // Change the font of the desired component and // all its contained components and menus. public static void setFont( Component c, Font f ) { if( c instanceof JMenu ) { JMenu mnu = (JMenu) c; for(int i = 0; i < mnu.getMenuComponentCount(); i++) setFont( mnu.getMenuComponent(i), f ); } else if( c instanceof Container ) { Container cont = (Container) c; for(int i = 0; i < cont.getComponentCount(); i++) setFont( cont.getComponent(i), f ); } c.setFont( f ); } }

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page lvii

Workshop 8: Using a List Model

ListDemo.java // ListDemo.java // ListModel Exercise import java.awt.*; import java.awt.event.*; import javax.swing.*; class ListDemo extends JFrame { private JTextField text_ = new JTextField(); private DefaultListModel model_ = new DefaultListModel(); public static void main(String[] args) { new ListDemo(args); } private ListDemo(String[] args) { super("JList & ListModel Demonstration"); JList list = new JList(); getContentPane().add(BorderLayout.NORTH, text_); getContentPane().add(BorderLayout.CENTER, new JScrollPane(list)); JButton btn = new JButton("Add Name to Model"); getContentPane().add(BorderLayout.SOUTH, btn); pack(); // Button event handler btn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { model_.addElement( text_.getText() ); text_.setText(""); text_.requestFocus(); } }); // Load a few names into the model

© 2003 SkillBuilders Inc.

V 2.1

Java SWing: Workshop Solutions

Page lviii

String[] names = { "Berlin", "Beethoven", "Bach", "Berlioz", "Gershwin", "Lennon", "McCartney", "Mozart", "Stravinsky" }; for( int i = 0; i < names.length; i++ ) model_.addElement( names[i] ); // Apply model list.setModel( model_ ); // Use default closing mechanism to close frame setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); setBounds( 200, 100, 300, 400 );

// Size frame

// Set font of entire frame just before showing. FontSetter.setFont( this, new Font("SansSerif", Font.PLAIN, 20) ); show(); } // End of c'tor } // End of class // // // // //

FontSetter is a convenience class. Its one static method, setFont(), is used to change the font setting for all components in a container. This is simply to make the font bigger for display purposes; it has no bearing on the exercise.

class FontSetter { // Change the font of the desired component and // all its contained components and menus. public static void setFont( Component c, Font f ) { if( c instanceof JMenu ) { JMenu mnu = (JMenu) c; for(int i = 0; i < mnu.getMenuComponentCount(); i++) setFont( mnu.getMenuComponent(i), f ); } else if( c instanceof Container ) { Container cont = (Container) c; for(int i = 0; i < cont.getComponentCount(); i++) setFont( cont.getComponent(i), f ); } c.setFont( f ); } }

© 2003 SkillBuilders Inc.

V 2.1

Related Documents

Java Swing
June 2020 9
Java Swing
April 2020 10
Java Swing
June 2020 10
Java Swing
November 2019 9
Java Swing Tutorial
July 2020 6

More Documents from ""