|
Home | Résumé | Courses | Contact | Useful Links | Favorite Links | USC - Homepage |
Computer Science 1 - (CPTR151) - Lectures
Lecture 14 - Version 1.2.1
Lecture Outline
14.1 Introduction
14.2 JTextArea
14.3 JSlider
14.4 Windows: Additional Notes
14.5 Using Menus with Frames
14.6 JPopupMenu
14.7 Pluggable Look-and-Feel
14.8 JDesktopPane and JInternalFrame
14.9 JTabbedPane
14.10 Layout Managers: BoxLayout and GridBagLayout
14.11 (Optional Case Study) Thinking About Objects: Model-View- Controller
14.14 (Optional) Discovering Design Patterns: Design Patterns Used in Packages java.awt and javax.swing
14.14.1 Creational Design Patterns
14.14.2 Structural Design Patterns
14.14.3 Behavioral Design Patterns
14.14.4 Conclusion
14.1 Introduction
• Advanced GUI components– Text areas– Sliders– Menus• Multiple Document Interface (MDI)• Advanced layout managers– BoxLayout– GridBagLayout
14.2 JTextArea
• JTextArea
– Area for manipulating multiple lines of text
– extends JTextComponent
1 // Fig. 14.1: TextAreaDemo.java2 // Copying selected text from one textarea to another.3 import java.awt.*;4 import java.awt.event.*;5 import javax.swing.*;67 public class TextAreaDemo extends JFrame {8 private JTextArea textArea1, textArea2;9 private JButton copyButton;1011 // set up GUI12 public TextAreaDemo()13 {14 super( "TextArea Demo" );1516 Box box = Box.createHorizontalBox();1718 String string = "This is a demo string to\n" + "illustrate copying text\nfrom one textarea to \n" +19 "another textarea using an\nexternal event\n";202122 // set up textArea123 textArea1 = new JTextArea( string, 10, 15 );24 box.add( new JScrollPane( textArea1 ) );2526 // set up copyButton27 copyButton = new JButton( "Copy >>>" );28 box.add( copyButton );29 copyButton.addActionListener(3031 new ActionListener() { // anonymous inner class3233 // set text in textArea2 to selected text from textArea134 public void actionPerformed( ActionEvent event )35 {36 textArea2.setText( textArea1.getSelectedText() );37 }3839 } // end anonymous inner class4041 ); // end call to addActionListener - Line 294243 // set up textArea244 textArea2 = new JTextArea( 10, 15 );45 textArea2.setEditable( false );46 box.add( new JScrollPane( textArea2 ) );4748 // add box to content pane49 Container container = getContentPane();50 container.add( box ); // place in BorderLayout.CENTER5152 setSize( 425, 200 );53 setVisible( true );5455 } // end constructor TextAreaDemo5657 public static void main( String args[ ] )58 {59 TextAreaDemo application = new TextAreaDemo();60 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );61 }6263 } // end class TextAreaDemo
Line 16 Create Box container for organizing GUI components
Lines 18-24 Populate JTextArea with String, then add to Box
Line 36 When user presses JButton, textArea1’s highlighted text is copied into textArea2
Lines 44-45 Instantiate uneditable JTextArea
14.3 JSlider
• JSlider– Enable users to select from range of integer values– Several features• Tick marks (major and minor)• Snap-to ticks• Orientation (horizontal and vertical)
Fig. 14.6 JSlider component with horizontal orientation
1 // Fig. 14.7: OvalPanel.java2 // A customized JPanel class.3 import java.awt.*;4 import javax.swing.*;56 public class OvalPanel extends JPanel {7 private int diameter = 10;89 // draw an oval of the specified diameter10 public void paintComponent( Graphics g )11 {12 super.paintComponent( g );1314 g.fillOval( 10, 10, diameter, diameter );15 }1617 // validate and set diameter, then repaint18 public void setDiameter( int newDiameter )19 {20 // if diameter invalid, default to 1021 diameter = ( newDiameter >= 0 ? newDiameter : 10 );22 repaint();23 }2425 // used by layout manager to determine preferred size26 public Dimension getPreferredSize()27 {28 return new Dimension( 200, 200 );29 }3031 // used by layout manager to determine minimum size32 public Dimension getMinimumSize()33 {34 return getPreferredSize();35 }3637 } // end class OvalPanel
1 // Fig. 14.8: SliderDemo.java2 // Using JSliders to size an oval.3 import java.awt.*;4 import java.awt.event.*;5 import javax.swing.*;6 import javax.swing.event.*;78 public class SliderDemo extends JFrame {9 private JSlider diameterSlider;10 private OvalPanel myPanel;1112 // set up GUI13 public SliderDemo()14 {15 super( "Slider Demo" );1617 // set up OvalPanel18 myPanel = new OvalPanel();19 myPanel.setBackground( Color.YELLOW );2021 // set up JSlider to control diameter value22 diameterSlider = new JSlider( SwingConstants.HORIZONTAL, 0, 200, 10 );2324 diameterSlider.setMajorTickSpacing( 10 );25 diameterSlider.setPaintTicks( true );2627 // register JSlider event listener28 diameterSlider.addChangeListener(2930 new ChangeListener() { // anonymous inner class3132 // handle change in slider value33 public void stateChanged( ChangeEvent e )34 {35 myPanel.setDiameter( diameterSlider.getValue() );36 }3738 } // end anonymous inner class3940 ); // end call to addChangeListener - line 284142 // attach components to content pane43 Container container = getContentPane();44 container.add( diameterSlider, BorderLayout.SOUTH );45 container.add( myPanel, BorderLayout.CENTER );4647 setSize( 220, 270 );48 setVisible( true );4950 } // end constructor SliderDemo5152 public static void main( String args[ ] )53 {54 SliderDemo application = new SliderDemo();55 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );56 }5758 } // end class SliderDemo
Lines 18-19 Instantiate OvalPanel object and set background to yellow
Lines 22-23 Instantiate horizontal JSlider object with min. value of 0, max. value of 200 and initial thumb location at 10
Line 28 Register anonymous ChangeListener object to handle JSlider events
Line 35 When user accesses JSlider, set OvalPanel’s diameter according to JSlider value
![]()
14.4 Windows: Additional Notes
• JFrame– Windows with title bar and border– Subclass of java.awt.Frame• Subclass of java.awt.Window– Heavyweight component– Three operations when user closes window• DISPOSE_ON_CLOSE• DO_NOTHING_ON_CLOSE
• HIDE_ON_CLOSE
14.5 Using Menus with Frames
• Menus– Allows for performing actions with cluttering GUI– Contained by menu bar• JMenuBar– Comprised of menu items• JMenuItem
1 // Fig. 14.9: MenuTest.java
2 // Demonstrating menus3 import java.awt.*;4 import java.awt.event.*;5 import javax.swing.*;67 public class MenuTest extends JFrame {8 private final Color colorValues[ ] = { Color.BLACK, Color.BLUE, Color.RED, Color.GREEN };910 private JRadioButtonMenuItem colorItems[ ], fonts[ ];11 private JCheckBoxMenuItem styleItems[ ];12 private JLabel displayLabel;13 private ButtonGroup fontGroup, colorGroup;14 private int style;1516 // set up GUI17 public MenuTest()18 {19 super( "Using JMenus" );2021 // set up File menu and its menu items22 JMenu fileMenu = new JMenu( "File" );23 fileMenu.setMnemonic( 'F' );2425 // set up About... menu item26 JMenuItem aboutItem = new JMenuItem( "About..." );27 aboutItem.setMnemonic( 'A' );28 fileMenu.add( aboutItem );29 aboutItem.addActionListener(3031 new ActionListener() { // anonymous inner class3233 // display message dialog when user selects About...34 public void actionPerformed( ActionEvent event )35 {36 JOptionPane.showMessageDialog( MenuTest.this,37 "This is an example\nof using menus", "About", JOptionPane.PLAIN_MESSAGE );38 }394041 } // end anonymous inner class4243 ); // end call to addActionListener4445 // set up Exit menu item46 JMenuItem exitItem = new JMenuItem( "Exit" );47 exitItem.setMnemonic( 'x' );48 fileMenu.add( exitItem );49 exitItem.addActionListener(5051 new ActionListener() { // anonymous inner class5253 // terminate application when user clicks exitItem54 public void actionPerformed( ActionEvent event )55 {56 System.exit( 0 );57 }5859 } // end anonymous inner class6061 ); // end call to addActionListener6263 // create menu bar and attach it to MenuTest window64 JMenuBar bar = new JMenuBar();65 setJMenuBar( bar );66 bar.add( fileMenu );6768 // create Format menu, its submenus and menu items69 JMenu formatMenu = new JMenu( "Format" );70 formatMenu.setMnemonic( 'r' );7172 // create Color submenu73 String colors[ ] = { "Black", "Blue", "Red", "Green" };7475 JMenu colorMenu = new JMenu( "Color" );76 colorMenu.setMnemonic( 'C' );7778 colorItems = new JRadioButtonMenuItem[ colors.length ];79 colorGroup = new ButtonGroup();80 ItemHandler itemHandler = new ItemHandler();8182 // create color radio button menu items83 for ( int count = 0; count < colors.length; count++ ) {84 colorItems[ count ] = new JRadioButtonMenuItem( colors[ count ] );8586 colorMenu.add( colorItems[ count ] );87 colorGroup.add( colorItems[ count ] );88 colorItems[ count ].addActionListener( itemHandler );89 }9091 // select first Color menu item92 colorItems[ 0 ].setSelected( true );9394 // add format menu to menu bar95 formatMenu.add( colorMenu );96 formatMenu.addSeparator();9798 // create Font submenu99 String fontNames[ ] = { "Serif", "Monospaced", "SansSerif" };100101 JMenu fontMenu = new JMenu( "Font" );102 fontMenu.setMnemonic( 'n' );103104 fonts = new JRadioButtonMenuItem[ fontNames.length ];105 fontGroup = new ButtonGroup();106107 // create Font radio button menu items108 for ( int count = 0; count < fonts.length; count++ ) {109 fonts[ count ] = new JRadioButtonMenuItem( fontNames[ count ] );110 fontMenu.add( fonts[ count ] );111 fontGroup.add( fonts[ count ] );112 fonts[ count ].addActionListener( itemHandler );113 }114115 // select first Font menu item116 fonts[ 0 ].setSelected( true );117118 fontMenu.addSeparator();119120 // set up style menu items121 String styleNames[ ] = { "Bold", "Italic" };122123 styleItems = new JCheckBoxMenuItem[ styleNames.length ];124 StyleHandler styleHandler = new StyleHandler();125126 // create style checkbox menu items127 for ( int count = 0; count < styleNames.length; count++ ) {128 styleItems[ count ] = new JCheckBoxMenuItem( styleNames[ count ] );129130 fontMenu.add( styleItems[ count ] );131 styleItems[ count ].addItemListener( styleHandler );132 }133134 // put Font menu in Format menu135 formatMenu.add( fontMenu );136137 // add Format menu to menu bar138 bar.add( formatMenu );139140 // set up label to display text141 displayLabel = new JLabel( "Sample Text", SwingConstants.CENTER );142 displayLabel.setForeground( colorValues[ 0 ] );143 displayLabel.setFont( new Font( "Serif", Font.PLAIN, 72 ) );144145 getContentPane().setBackground( Color.CYAN );146 getContentPane().add( displayLabel, BorderLayout.CENTER );147148 setSize( 500, 200 );149 setVisible( true );150151 } // end constructor152153 public static void main( String args[ ] )154 {155 MenuTest application = new MenuTest();156 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );157 }158159 // inner class to handle action events from menu items160 private class ItemHandler implements ActionListener {161162 // process color and font selections163 public void actionPerformed( ActionEvent event )164 {165 // process color selection166 for ( int count = 0; count < colorItems.length; count++ )167168 if ( colorItems[ count ].isSelected() ) {169 displayLabel.setForeground( colorValues[ count ] );170 break;171 }172173 // process font selection174 for ( int count = 0; count < fonts.length; count++ )175176 if ( event.getSource() == fonts[ count ] ) {177 displayLabel.setFont(new Font( fonts[ count ].getText(), style, 72 ) );178 break;179 }180181182 repaint();183184 } // end method actionPerformed185186 } // end class ItemHandler187188 // inner class to handle item events from check box menu items189 private class StyleHandler implements ItemListener {190191 // process font style selections192 public void itemStateChanged( ItemEvent e )193 {194 style = 0;195196 // check for bold selection197 if ( styleItems[ 0 ].isSelected() )198 style += Font.BOLD;199200 // check for italic selection201 if ( styleItems[ 1 ].isSelected() )202 style += Font.ITALIC;203204 displayLabel.setFont(new Font( displayLabel.getFont().getName(), style, 72 ) );205 repaint();206 }207208209210 } // end class StyleHandler211212 } // end class MenuTest
Line 22 Instantiate File JMenu
Line 26 Instantiate About… JMenuItem to be placed in fileMenu
Lines 36-38 When user selects About… JMenuItem, display message dialog with appropriate text
Line 46 Instantiate Exit JMenuItem to be placed in fileMenu
Line 56 When user selects Exit JMenuItem, exit system
Line 64 Instantiate JMenuBar to contain JMenus
Line 69 Instantiate Format JMenuLine 75 Instantiate Color JMenu (submenu of Format JMenu)
Lines 78-79 Instantiate JRadioButtonMenuItems for Color JMenu and ensure that only one menu item is selected at a time
Line 96 Separator places line between JMenuItemsLine 101 Instantiate Font JMenu (submenu of Format JMenu)
Lines 104-105 Instantiate JRadioButtonMenuItems for Font JMenu and ensure that only one menu item is selected at a time
Line 163 Invoked when user selects JMenuItem
Lines 168 and 176 Determine which font or color menu generated event
Lines 169 and 177-178 Set font or color of JLabel, respectivelyLine 192 Invoked when user selects JCheckBoxMenuItem
Lines 197-202 Determine new font style
14.6 JPopupMenu
• Context-sensitive popup menus– JPopupMenu– Menu generated depending on which component is accessed
1 // Fig. 14.10: PopupTest.java2 // Demonstrating JPopupMenus3 import java.awt.*;4 import java.awt.event.*;5 import javax.swing.*;67 public class PopupTest extends JFrame {8 private JRadioButtonMenuItem items[ ];9 private final Color colorValues[ ] =10 { Color.BLUE, Color.YELLOW, Color.RED };11 private JPopupMenu popupMenu;1213 // set up GUI14 public PopupTest()15 {16 super( "Using JPopupMenus" );1718 ItemHandler handler = new ItemHandler();19 String colors[ ] = { "Blue", "Yellow", "Red" };2021 // set up popup menu and its items22 ButtonGroup colorGroup = new ButtonGroup();23 popupMenu = new JPopupMenu();24 items = new JRadioButtonMenuItem[ 3 ];2526 // construct each menu item and add to popup menu; also27 // enable event handling for each menu item28 for ( int count = 0; count < items.length; count++ ) {29 items[ count ] = new JRadioButtonMenuItem( colors[ count ] );30 popupMenu.add( items[ count ] );31 colorGroup.add( items[ count ] );32 items[ count ].addActionListener( handler );33 }3435 getContentPane().setBackground( Color.WHITE );3637 // declare a MouseListener for the window that displays38 // a JPopupMenu when the popup trigger event occurs39 addMouseListener(4041 new MouseAdapter() { // anonymous inner class4243 // handle mouse press event44 public void mousePressed( MouseEvent event )45 {46 checkForTriggerEvent( event );47 }4849 // handle mouse release event50 public void mouseReleased( MouseEvent event )51 {52 checkForTriggerEvent( event );53 }5455 // determine whether event should trigger popup menu56 private void checkForTriggerEvent( MouseEvent event )57 {58 if ( event.isPopupTrigger() )59 popupMenu.show(event.getComponent(), event.getX(), event.getY() );6061 }6263 } // end anonymous inner clas6465 ); // end call to addMouseListener - line 396667 setSize( 300, 200 );68 setVisible( true );6970 } // end constructor PopupTest7172 public static void main( String args[ ] )73 {74 PopupTest application = new PopupTest();75 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );76 }7778 // private inner class to handle menu item events79 private class ItemHandler implements ActionListener {8081 // process menu item selections82 public void actionPerformed( ActionEvent event )83 {84 // determine which menu item was selected85 for ( int i = 0; i < items.length; i++ )86 if ( event.getSource() == items[ i ] ) {87 getContentPane().setBackground( colorValues[ i ] );88 return;89 }90 }9192 } // end private inner class ItemHandler9394 } // end class PopupTest
Line 23 Instantiate JPopupMenu object
Lines 29-32 Create JRadioButtonMenuItem objects to add to JPopupMenu
Lines 46 and 52 Determine whether popup-trigger event occurred when user presses or releases mouse buttonLines 59-60 Show JPopupMenu if popup-trigger occurredLine 82 Invoked when user selects JRadioButtonMenuItem
Line 87 Determine which JRadioButtonMenuItem was selected, then set window background color
![]()
14.7 Pluggable Look-and-Feel
• Pluggable look-and-feel– Change look-and-feel dynamically• e.g., Microsoft Windows look-and-feel to Motif look-and-feel– Flexible
1 // Fig. 14.11: LookAndFeelDemo.java2 // Changing the look and feel.3 import java.awt.*;4 import java.awt.event.*;5 import javax.swing.*;67 public class LookAndFeelDemo extends JFrame {8 private final String strings[ ] = { "Metal", "Motif", "Windows" };9 private UIManager.LookAndFeelInfo looks[ ];10 private JRadioButton radio[ ];11 private ButtonGroup group;12 private JButton button;13 private JLabel label;14 private JComboBox comboBox;1516 // set up GUI17 public LookAndFeelDemo()18 {19 super( "Look and Feel Demo" );2021 Container container = getContentPane();2223 // set up panel for NORTH of BorderLayout24 JPanel northPanel = new JPanel();25 northPanel.setLayout( new GridLayout( 3, 1, 0, 5 ) );2627 // set up label for NORTH panel28 label = new JLabel( "This is a Metal look-and-feel", SwingConstants.CENTER );29 northPanel.add( label );303132 // set up button for NORTH panel33 button = new JButton( "JButton" );34 northPanel.add( button );3536 // set up combo box for NORTH panel37 comboBox = new JComboBox( strings );38 northPanel.add( comboBox );3940 // create array for radio buttons41 radio = new JRadioButton[ strings.length ];4243 // set up panel for SOUTH of BorderLayout44 JPanel southPanel = new JPanel();45 southPanel.setLayout( new GridLayout( 1, radio.length ) );4647 // set up radio buttons for SOUTH panel48 group = new ButtonGroup();49 ItemHandler handler = new ItemHandler();5051 for ( int count = 0; count < radio.length; count++ ) {52 radio[ count ] = new JRadioButton( strings[ count ] );53 radio[ count ].addItemListener( handler );54 group.add( radio[ count ] );55 southPanel.add( radio[ count ] );56 }5758 // attach NORTH and SOUTH panels to content pane59 container.add( northPanel, BorderLayout.NORTH );60 container.add( southPanel, BorderLayout.SOUTH );6162 // get installed look-and-feel information63 looks = UIManager.getInstalledLookAndFeels();6465 setSize( 300, 200 );66 setVisible( true );6768 radio[ 0 ].setSelected( true );6970 } // end constructor LookAndFeelDemo7172 // use UIManager to change look-and-feel of GUI73 private void changeTheLookAndFeel( int value )74 {75 // change look and feel76 try {77 UIManager.setLookAndFeel( looks[ value ].getClassName() );78 SwingUtilities.updateComponentTreeUI( this );79 }8081 // process problems changing look and feel82 catch ( Exception exception ) {83 exception.printStackTrace();84 }85 }8687 public static void main( String args[ ] )88 {89 LookAndFeelDemo application = new LookAndFeelDemo();90 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );91 }9293 // private inner class to handle radio button events94 private class ItemHandler implements ItemListener {9596 // process user's look-and-feel selection97 public void itemStateChanged( ItemEvent event )98 {99 for ( int count = 0; count < radio.length; count++ )100101 if ( radio[ count ].isSelected() ) {102 label.setText( "This is a " + strings[ count ] + " look-and-feel" );103104 comboBox.setSelectedIndex( count );105 changeTheLookAndFeel( count );106 }107 }108109 } // end private inner class ItemHandler110111 } // end class LookAndFeelDemo
Line 9 Hold installed look-and-feel informationLines 77-78 Change look-and-feel
14.8 JDesktopPane and JInternalFrame
• Multiple document interface– Main (parent) window– Child windows– Switch freely among documents
1 // Fig. 14.12: DesktopTest.java2 // Demonstrating JDesktopPane.3 import java.awt.*;4 import java.awt.event.*;5 import javax.swing.*;67 public class DesktopTest extends JFrame {8 private JDesktopPane theDesktop;