Download presentation
Presentation is loading. Please wait.
Published byMaximilian Patrick Modified over 9 years ago
1
2003 Prentice Hall, Inc. All rights reserved. 1 Outline 13.1 Introduction 13.2 Overview of Swing Components 13.3 JLabel 13.4 Event Handling 13.5 TextFields 13.6 How Event Handling Works 13.7 JButton 13.8 JCheckBox and JRadioButton 13.9 JComboBox 13.10 JList 13.12 Mouse Event Handling 13.13 Adapter Classes 13.14 Key Event Handling Chapters 13-14 - Graphical User Interface Components
2
2003 Prentice Hall, Inc. All rights reserved. 2 Outline 13.15 Layout Managers 13.15.1 FlowLayout 13.15.2 BorderLayout 13.15.3 GridLayout 13.16 Panels Chapters 13-14 - Graphical User Interface Components
3
2003 Prentice Hall, Inc. All rights reserved. 3 Chapters 13-14 - Graphical User Interface Components Outline 14.2 JTextArea 14.3 Creating a Customized Subclass of JPanel 14.4 JPanel Subclass that Handles Its Own Events 14.5 JSlider 14.7 Using Menus with Frames 14.11 JTabbedPane 14.14 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
4
2003 Prentice Hall, Inc. All rights reserved. 4 13.1 Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides users with basic level of familiarity –Built from GUI components -- controls, window gadgets (widgets), etc. User interacts with GUI component via mouse, keyboard, etc. –Using graphics and GUI classes helps to demonstrate the effectiveness of reusable code
5
2003 Prentice Hall, Inc. All rights reserved. 5 Fig. 13.1Netscape window with GUI components menu bar buttoncombo boxmenus scroll bars
6
2003 Prentice Hall, Inc. All rights reserved. 6 Fig. 13.2 Some basic GUI components
7
2003 Prentice Hall, Inc. All rights reserved. 7 13.2 Overview of Swing Components Swing GUI components –Package javax.swing –Components originated in Abstract Windows Toolkit (AWT) (package java.awt ) –Contain look and feel Appearance and how users interact with program –Lightweight (pure Java) components Written completely in Java Part of Java Foundation Classes (JFC)
8
2003 Prentice Hall, Inc. All rights reserved. 8 Fig. 13.3 Common superclasses of many of the Swing components Object Component Container JComponent Object Component JComponent Container
9
2003 Prentice Hall, Inc. All rights reserved. 9 13.2 Overview of Swing Components Class Component –Contains method paint for drawing Component onscreen Class Container –Collection of related components –Contains method add for adding components Class JComponent –Superclass of most Swing components –Pluggable look and feel for customizing appearance –Shortcut keys (mnemonics) for keyboard access to GUI components –Common event-handling capabilities
10
2003 Prentice Hall, Inc. All rights reserved. 10 13.3 JLabel Label –Provide text on GUI –Defined with class JLabel –Can display: Single line of read-only text Image Text and image setToolTipText method (from JComponent ) specifies text that appears when user moves cursor over JLabel
11
2003 Prentice Hall, Inc. All rights reserved. Outline 11 LabelTest.java Line 8 Line 20 Line 21 1 // Fig. 13.4: LabelTest.java 2 // Demonstrating the JLabel class. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class LabelTest extends JFrame { 8 private JLabel label1, label2, label3; 9 10 // set up GUI 11 public LabelTest() 12 { 13 super( "Testing JLabel" ); 14 15 // get content pane and set its layout 16 Container container = getContentPane(); 17 container.setLayout( new FlowLayout() ); 18 19 // JLabel constructor with a string argument 20 label1 = new JLabel( "Label with text" ); 21 label1.setToolTipText( "This is label1" ); 22 container.add( label1 ); 23 Declare three JLabel sCreate first JLabel with text “ Label with text ” Tool tip is text that appears when user moves cursor over JLabel
12
2003 Prentice Hall, Inc. All rights reserved. Outline 12 LabelTest.java Lines 26-27 Lines 32-37 24 // JLabel constructor with string, Icon and alignment arguments 25 Icon bug = new ImageIcon( "bug1.gif" ); 26 label2 = new JLabel( "Label with text and icon", bug, 27 SwingConstants.LEFT ); 28 label2.setToolTipText( "This is label2" ); 29 container.add( label2 ); 30 31 // JLabel constructor no arguments 32 label3 = new JLabel(); 33 label3.setText( "Label with icon and text at bottom" ); 34 label3.setIcon( bug ); 35 label3.setHorizontalTextPosition( SwingConstants.CENTER ); 36 label3.setVerticalTextPosition( SwingConstants.BOTTOM ); 37 label3.setToolTipText( "This is label3" ); 38 container.add( label3 ); 39 40 setSize( 275, 170 ); 41 setVisible( true ); 42 43 } // end constructor 44 45 public static void main( String args[] ) 46 { 47 LabelTest application = new LabelTest(); 48 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 49 } Create second JLabel with image to the left of the text Create third JLabel with text below image
13
2003 Prentice Hall, Inc. All rights reserved. Outline 13 LabelTest.java 50 51 } // end class LabelTest
14
2003 Prentice Hall, Inc. All rights reserved. 14 13.4 Event Handling GUIs are event driven –Generate events when user interacts with GUI e.g., moving the mouse, clicking a button, typing in text field, selecting menu item, etc. Class java.awt.AWTEvent
15
2003 Prentice Hall, Inc. All rights reserved. 15 13.4 Event Handling Java Event Model –Three parts Event source –GUI component with which user interacts Event object –Encapsulates information about event that occurred Event listener –Receives event object when notified, then responds –Programmer must perform two tasks Register event listener for event source Implement event-handling method (event handler)
16
2003 Prentice Hall, Inc. All rights reserved. 16 13.5 TextFields JTextField –Single-line area in which user can enter text –setEditable(false), user cannot modify textfield JPasswordField –Extends JTextField –Hides characters that user enters
17
2003 Prentice Hall, Inc. All rights reserved. Outline 17 TextFieldTest.j ava Lines 8-9 Line 20 Line 24 1 // Fig. 13.7: TextFieldTest.java 2 // Demonstrating the JTextField class. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class TextFieldTest extends JFrame { 8 private JTextField textField1, textField2, textField3; 9 private JPasswordField passwordField; 10 11 // set up GUI 12 public TextFieldTest() 13 { 14 super( "Testing JTextField and JPasswordField" ); 15 16 Container container = getContentPane(); 17 container.setLayout( new FlowLayout() ); 18 19 // construct textfield with default sizing 20 textField1 = new JTextField( 10 ); 21 container.add( textField1 ); 22 23 // construct textfield with default text 24 textField2 = new JTextField( "Enter text here" ); 25 container.add( textField2 ); 26 Declare three JTextField s and one JPasswordField First JTextField contains empty string Second JTextField contains text “ Enter text here ”
18
2003 Prentice Hall, Inc. All rights reserved. Outline 18 TextFieldTest.j ava Line 30 Line 34 Lines 39-42 27 // construct textfield with default text, 28 // 20 visible elements and no event handler 29 textField3 = new JTextField( "Uneditable text field", 20 ); 30 textField3.setEditable( false ); 31 container.add( textField3 ); 32 33 // construct passwordfield with default text 34 passwordField = new JPasswordField( "Hidden text" ); 35 container.add( passwordField ); 36 37 // register event handlers 38 TextFieldHandler handler = new TextFieldHandler(); 39 textField1.addActionListener( handler ); 40 textField2.addActionListener( handler ); 41 textField3.addActionListener( handler ); 42 passwordField.addActionListener( handler ); 43 44 setSize( 325, 100 ); 45 setVisible( true ); 46 47 } // end constructor TextFieldTest 48 49 public static void main( String args[] ) 50 { 51 TextFieldTest application = new TextFieldTest(); 52 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 53 } Third JTextField contains uneditable text JPasswordField contains text “ Hidden text,” but text appears as series of asterisks ( * ) Register GUI components with TextFieldHandler (register for ActionEvent s)
19
2003 Prentice Hall, Inc. All rights reserved. Outline 19 TextFieldTest.j ava Line 56 Line 59 54 55 // private inner class for event handling 56 private class TextFieldHandler implements ActionListener { 57 58 // process textfield events 59 public void actionPerformed( ActionEvent event ) 60 { 61 String string = ""; 62 63 // user pressed Enter in JTextField textField1 64 if ( event.getSource() == textField1 ) 65 string = "textField1: " + event.getActionCommand(); 66 67 // user pressed Enter in JTextField textField2 68 else if ( event.getSource() == textField2 ) 69 string = "textField2: " + event.getActionCommand(); 70 71 // user pressed Enter in JTextField textField3 72 else if ( event.getSource() == textField3 ) 73 string = "textField3: " + event.getActionCommand(); 74 75 // user pressed Enter in JTextField passwordField 76 else if ( event.getSource() == passwordField ) { 77 string = "passwordField: " + 78 new String( passwordField.getPassword() ); 79 } Every TextFieldHandler instance is an ActionListener Method actionPerformed invoked when user presses Enter in GUI field
20
2003 Prentice Hall, Inc. All rights reserved. Outline 20 TextFieldTest.j ava 80 81 JOptionPane.showMessageDialog( null, string ); 82 83 } // end method actionPerformed 84 85 } // end private inner class TextFieldHandler 86 87 } // end class TextFieldTest
21
2003 Prentice Hall, Inc. All rights reserved. Outline 21 TextFieldTest.j ava
22
2003 Prentice Hall, Inc. All rights reserved. 22 13.6 How Event Handling Works Two open questions –How did event handler get registered? Answer: –Through component’s method addActionListener –Lines 39-42 of TextFieldTest.java –How does component know to call actionPerformed ? Answer: –Event is dispatched only to listeners of appropriate type –Each event type has corresponding event-listener interface Event ID specifies event type that occurred –getSource returns object that generated event –getActionCommand returns text in textfield
23
2003 Prentice Hall, Inc. All rights reserved. 23 Fig. 13.8 Event registration for JTextField textField1 textField1 listenerList... handler This reference is created by the statement textField1.addActionListener( handler ); public void actionPerformed( ActionEvent event ) { // event handled here } JTextField object TextFieldHandler object
24
2003 Prentice Hall, Inc. All rights reserved. 24 13.7 JButton Button –Component user clicks to trigger a specific action –Several different types Command buttons Check boxes Toggle buttons Radio buttons –javax.swing.AbstractButton subclasses Command buttons are created with class JButton –Text on button face called “button label” –Button can have icon and rollover icon –Generate ActionEvent s when user clicks button –getActionCommand returns button label
25
2003 Prentice Hall, Inc. All rights reserved. Outline 25 ButtonTest.java Line 8 Line 20 Lines 24-26 1 // Fig. 13.10: ButtonTest.java 2 // Creating JButtons. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class ButtonTest extends JFrame { 8 private JButton plainButton, fancyButton; 9 10 // set up GUI 11 public ButtonTest() 12 { 13 super( "Testing Buttons" ); 14 15 // get content pane and set its layout 16 Container container = getContentPane(); 17 container.setLayout( new FlowLayout() ); 18 19 // create buttons 20 plainButton = new JButton( "Plain Button" ); 21 container.add( plainButton ); 22 23 Icon bug1 = new ImageIcon( "bug1.gif" ); 24 Icon bug2 = new ImageIcon( "bug2.gif" ); 25 fancyButton = new JButton( "Fancy Button", bug1 ); 26 fancyButton.setRolloverIcon( bug2 ); 27 container.add( fancyButton ); Create two references to JButton instances Instantiate JButton with textInstantiate JButton with image and rollover image
26
2003 Prentice Hall, Inc. All rights reserved. Outline 26 ButtonTest.java Line 31 Lines 32-33 Line 50 28 29 // create an instance of inner class ButtonHandler 30 // to use for button event handling 31 ButtonHandler handler = new ButtonHandler(); 32 fancyButton.addActionListener( handler ); 33 plainButton.addActionListener( handler ); 34 35 setSize( 275, 100 ); 36 setVisible( true ); 37 38 } // end ButtonTest constructor 39 40 public static void main( String args[] ) 41 { 42 ButtonTest application = new ButtonTest(); 43 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 44 } 45 46 // inner class for button event handling 47 private class ButtonHandler implements ActionListener { 48 49 // handle button event 50 public void actionPerformed( ActionEvent event ) 51 { 52 JOptionPane.showMessageDialog( ButtonTest.this, 53 "You pressed: " + event.getActionCommand() ); 54 } Instantiate ButtonHandler for JButton event handling Register JButton s to receive events from ButtonHandler When user clicks JButton, ButtonHandler invokes method actionPerformed of all registered listeners
27
2003 Prentice Hall, Inc. All rights reserved. Outline 27 ButtonTest.java 55 56 } // end private inner class ButtonHandler 57 58 } // end class ButtonTest
28
2003 Prentice Hall, Inc. All rights reserved. 28 13.8 JCheckBox and JRadioButton State buttons –On/Off or true / false values –Java provides three types JToggleButton JCheckBox JRadioButton –getSource returns button object that generated event –isSelected tells if a JCheckBox has been selected or not –JRadioButton s normally appear as a ButtonGroup –JRadioButton s are mutually exclusive (old time radio buttons)
29
2003 Prentice Hall, Inc. All rights reserved. Outline 29 CheckBoxTest.ja va Line 9 Line 22 1 // Fig. 13.11: CheckBoxTest.java 2 // Creating JCheckBox buttons. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class CheckBoxTest extends JFrame { 8 private JTextField field; 9 private JCheckBox bold, italic; 10 11 // set up GUI 12 public CheckBoxTest() 13 { 14 super( "JCheckBox Test" ); 15 16 // get content pane and set its layout 17 Container container = getContentPane(); 18 container.setLayout( new FlowLayout() ); 19 20 // set up JTextField and set its font 21 field = new JTextField( "Watch the font style change", 20 ); 22 field.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); 23 container.add( field ); 24 Declare two JCheckBox instancesSet JTextField font to Serif, 14-point plain
30
2003 Prentice Hall, Inc. All rights reserved. Outline 30 CheckBoxTest.ja va Lines 26 and 29 Lines 34-35 25 // create checkbox objects 26 bold = new JCheckBox( "Bold" ); 27 container.add( bold ); 28 29 italic = new JCheckBox( "Italic" ); 30 container.add( italic ); 31 32 // register listeners for JCheckBoxes 33 CheckBoxHandler handler = new CheckBoxHandler(); 34 bold.addItemListener( handler ); 35 italic.addItemListener( handler ); 36 37 setSize( 275, 100 ); 38 setVisible( true ); 39 40 } // end CheckBoxText constructor 41 42 public static void main( String args[] ) 43 { 44 CheckBoxTest application = new CheckBoxTest(); 45 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 46 } 47 Instantiate JCheckBox s for bolding and italicizing JTextField text, respectively Register JCheckBox s to receive events from CheckBoxHandler
31
2003 Prentice Hall, Inc. All rights reserved. Outline 31 CheckBoxTest.ja va Line 54 Line 65 48 // private inner class for ItemListener event handling 49 private class CheckBoxHandler implements ItemListener { 50 private int valBold = Font.PLAIN; 51 private int valItalic = Font.PLAIN; 52 53 // respond to checkbox events 54 public void itemStateChanged( ItemEvent event ) 55 { 56 // process bold checkbox events 57 if ( event.getSource() == bold ) 58 valBold = bold.isSelected() ? Font.BOLD : Font.PLAIN; 59 60 // process italic checkbox events 61 if ( event.getSource() == italic ) 62 valItalic = italic.isSelected() ? Font.ITALIC : Font.PLAIN; 63 64 // set text field font 65 field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); 66 67 } // end method itemStateChanged 68 69 } // end private inner class CheckBoxHandler 70 71 } // end class CheckBoxTest When user selects JCheckBox, CheckBoxHandler invokes method itemStateChanges of all registered listeners Change JTextField font, depending on which JCheckBox was selected
32
2003 Prentice Hall, Inc. All rights reserved. Outline 32 CheckBoxTest.ja va
33
2003 Prentice Hall, Inc. All rights reserved. Outline 33 RadioButtonTest.java Lines 10-11 Line 12 1 // Fig. 13.12: RadioButtonTest.java 2 // Creating radio buttons using ButtonGroup and JRadioButton. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class RadioButtonTest extends JFrame { 8 private JTextField field; 9 private Font plainFont, boldFont, italicFont, boldItalicFont; 10 private JRadioButton plainButton, boldButton, italicButton, 11 boldItalicButton; 12 private ButtonGroup radioGroup; 13 14 // create GUI and fonts 15 public RadioButtonTest() 16 { 17 super( "RadioButton Test" ); 18 19 // get content pane and set its layout 20 Container container = getContentPane(); 21 container.setLayout( new FlowLayout() ); 22 23 // set up JTextField 24 field = new JTextField( "Watch the font style change", 25 ); 25 container.add( field ); 26 JRadioButton s normally appear as a ButtonGroup Declare four JRadioButton instances
34
2003 Prentice Hall, Inc. All rights reserved. Outline 34 RadioButtonTest.java Lines 28-35 Lines 41-45 27 // create radio buttons 28 plainButton = new JRadioButton( "Plain", true ); 29 container.add( plainButton ); 30 31 boldButton = new JRadioButton( "Bold", false ); 32 container.add( boldButton ); 33 34 italicButton = new JRadioButton( "Italic", false ); 35 container.add( italicButton ); 36 37 boldItalicButton = new JRadioButton( "Bold/Italic", false ); 38 container.add( boldItalicButton ); 39 40 // create logical relationship between JRadioButtons 41 radioGroup = new ButtonGroup(); 42 radioGroup.add( plainButton ); 43 radioGroup.add( boldButton ); 44 radioGroup.add( italicButton ); 45 radioGroup.add( boldItalicButton ); 46 47 // create font objects 48 plainFont = new Font( "Serif", Font.PLAIN, 14 ); 49 boldFont = new Font( "Serif", Font.BOLD, 14 ); 50 italicFont = new Font( "Serif", Font.ITALIC, 14 ); 51 boldItalicFont = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 ); 52 field.setFont( plainFont ); // set initial font 53 Instantiate JRadioButton s for manipulating JTextField text font JRadioButton s belong to ButtonGroup
35
2003 Prentice Hall, Inc. All rights reserved. Outline 35 RadioButtonTest.java Lines 55-60 54 // register events for JRadioButtons 55 plainButton.addItemListener( new RadioButtonHandler( plainFont ) ); 56 boldButton.addItemListener( new RadioButtonHandler( boldFont ) ); 57 italicButton.addItemListener( 58 new RadioButtonHandler( italicFont ) ); 59 boldItalicButton.addItemListener( 60 new RadioButtonHandler( boldItalicFont ) ); 61 62 setSize( 300, 100 ); 63 setVisible( true ); 64 65 } // end RadioButtonTest constructor 66 67 public static void main( String args[] ) 68 { 69 RadioButtonTest application = new RadioButtonTest(); 70 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 71 } 72 73 // private inner class to handle radio button events 74 private class RadioButtonHandler implements ItemListener { 75 private Font font; 76 77 public RadioButtonHandler( Font f ) 78 { 79 font = f; 80 } Register JRadioButton s to receive events from RadioButtonHandler
36
2003 Prentice Hall, Inc. All rights reserved. Outline 36 RadioButtonTest.java Line 83 Line 85 81 82 // handle radio button events 83 public void itemStateChanged( ItemEvent event ) 84 { 85 field.setFont( font ); 86 } 87 88 } // end private inner class RadioButtonHandler 89 90 } // end class RadioButtonTest When user selects JRadioButton, RadioButtonHandler invokes method itemStateChanged of all registered listeners Set font corresponding to JRadioButton selected
37
2003 Prentice Hall, Inc. All rights reserved. 37 13.9 JComboBox JComboBox –List of items from which user can select –Also called a drop-down list –setMaximumRowCount sets max number of elements displayed when user clicks on combo box –getSelectedIndex tells which item in the combo box was selected
38
2003 Prentice Hall, Inc. All rights reserved. Outline 38 ComboBoxTest.ja va 1 // Fig. 13.13: ComboBoxTest.java 2 // Using a JComboBox to select an image to display. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class ComboBoxTest extends JFrame { 8 private JComboBox imagesComboBox; 9 private JLabel label; 10 11 private String names[] = 12 { "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" }; 13 private Icon icons[] = { new ImageIcon( names[ 0 ] ), 14 new ImageIcon( names[ 1 ] ), new ImageIcon( names[ 2 ] ), 15 new ImageIcon( names[ 3 ] ) }; 16 17 // set up GUI 18 public ComboBoxTest() 19 { 20 super( "Testing JComboBox" ); 21 22 // get content pane and set its layout 23 Container container = getContentPane(); 24 container.setLayout( new FlowLayout() ); 25
39
2003 Prentice Hall, Inc. All rights reserved. Outline 39 ComboBoxTest.ja va Lines 27-28 Line 29 Line 34 Lines 38-39 26 // set up JComboBox and register its event handler 27 imagesComboBox = new JComboBox( names ); 28 imagesComboBox.setMaximumRowCount( 3 ); 29 imagesComboBox.addItemListener( 30 31 new ItemListener() { // anonymous inner class 32 33 // handle JComboBox event 34 public void itemStateChanged( ItemEvent event ) 35 { 36 // determine whether check box selected 37 if ( event.getStateChange() == ItemEvent.SELECTED ) 38 label.setIcon( icons[ 39 imagesComboBox.getSelectedIndex() ] ); 40 } 41 42 } // end anonymous inner class 43 44 ); // end call to addItemListener 45 46 container.add( imagesComboBox ); 47 48 // set up JLabel to display ImageIcons 49 label = new JLabel( icons[ 0 ] ); 50 container.add( label ); 51 Register JComboBox to receive events from anonymous ItemListener Instantiate JComboBox to show three String s from names array at a time When user selects item in JComboBox, ItemListener invokes method itemStateChanged of all registered listeners Set appropriate Icon depending on user selection
40
2003 Prentice Hall, Inc. All rights reserved. Outline 40 ComboBoxTest.ja va 52 setSize( 350, 100 ); 53 setVisible( true ); 54 55 } // end ComboBoxTest constructor 56 57 public static void main( String args[] ) 58 { 59 ComboBoxTest application = new ComboBoxTest(); 60 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 61 } 62 63 } // end class ComboBoxTest
41
2003 Prentice Hall, Inc. All rights reserved. 41 13.10 JList List –Series of items –user can select one or more items –single-selection and multiple-selection lists –JList does not provide scrollbar, JScrollPane necessary –getSelectedIndex tells which item in the list was selected
42
2003 Prentice Hall, Inc. All rights reserved. Outline 42 ListTest.java 1 // Fig. 13.14: ListTest.java 2 // Selecting colors from a JList. 3 import java.awt.*; 4 import javax.swing.*; 5 import javax.swing.event.*; 6 7 public class ListTest extends JFrame { 8 private JList colorList; 9 private Container container; 10 11 private final String colorNames[] = { "Black", "Blue", "Cyan", 12 "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", 13 "Orange", "Pink", "Red", "White", "Yellow" }; 14 15 private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN, 16 Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, 17 Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, 18 Color.YELLOW }; 19 20 // set up GUI 21 public ListTest() 22 { 23 super( "List Test" ); 24 25 // get content pane and set its layout 26 container = getContentPane(); 27 container.setLayout( new FlowLayout() );
43
2003 Prentice Hall, Inc. All rights reserved. Outline 43 ListTest.java Line 30 Line 34 Line 38 Line 43 Lines 45-46 28 29 // create a list with items in colorNames array 30 colorList = new JList( colorNames ); 31 colorList.setVisibleRowCount( 5 ); 32 33 // do not allow multiple selections 34 colorList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); 35 36 // add a JScrollPane containing JList to content pane 37 container.add( new JScrollPane( colorList ) ); 38 colorList.addListSelectionListener( 39 40 new ListSelectionListener() { // anonymous inner class 41 42 // handle list selection events 43 public void valueChanged( ListSelectionEvent event ) 44 { 45 container.setBackground( 46 colors[ colorList.getSelectedIndex() ] ); 47 } 48 49 } // end anonymous inner class 50 51 ); // end call to addListSelectionListener 52 Use colorNames array to populate JList JList allows single selections Register JList to receive events from anonymous ListSelectionListener When user selects item in JList, ListSelectionListener invokes method valueChanged of all registered listeners Set appropriate background depending on user selection
44
2003 Prentice Hall, Inc. All rights reserved. Outline 44 ListTest.java 53 setSize( 350, 150 ); 54 setVisible( true ); 55 56 } // end ListTest constructor 57 58 public static void main( String args[] ) 59 { 60 ListTest application = new ListTest(); 61 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 62 } 63 64 } // end class ListTest
45
2003 Prentice Hall, Inc. All rights reserved. 45 13.12 Mouse Event Handling Event-listener interfaces for mouse events –MouseListener –MouseMotionListener –MouseEvent object tells what event occurred and the x and y coordinates ( e.getX() and e.getY() )
46
2003 Prentice Hall, Inc. All rights reserved. 46 Fig. 13.16 MouseListener and MouseMotionListener interface methods
47
2003 Prentice Hall, Inc. All rights reserved. Outline 47 MouseTracker.ja va Lines 20-21 1 // Fig. 13.17: MouseTracker.java 2 // Demonstrating mouse events. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class MouseTracker extends JFrame 8 implements MouseListener, MouseMotionListener { 9 10 private JLabel statusBar; 11 12 // set up GUI and register mouse event handlers 13 public MouseTracker() 14 { 15 super( "Demonstrating Mouse Events" ); 16 17 statusBar = new JLabel(); 18 getContentPane().add( statusBar, BorderLayout.SOUTH ); 19 20 addMouseListener( this ); // listens for own mouse and 21 addMouseMotionListener( this ); // mouse-motion events 22 23 setSize( 275, 100 ); 24 setVisible( true ); 25 } 26 Register JFrame to receive mouse events
48
2003 Prentice Hall, Inc. All rights reserved. Outline 48 MouseTracker.ja va Line 29 Line 36 Line 43 Line 50 27 // MouseListener event handlers 28 // handle event when mouse released immediately after press 29 public void mouseClicked( MouseEvent event ) 30 { 31 statusBar.setText( "Clicked at [" + event.getX() + 32 ", " + event.getY() + "]" ); 33 } 34 35 // handle event when mouse pressed 36 public void mousePressed( MouseEvent event ) 37 { 38 statusBar.setText( "Pressed at [" + event.getX() + 39 ", " + event.getY() + "]" ); 40 } 41 42 // handle event when mouse released after dragging 43 public void mouseReleased( MouseEvent event ) 44 { 45 statusBar.setText( "Released at [" + event.getX() + 46 ", " + event.getY() + "]" ); 47 } 48 49 // handle event when mouse enters area 50 public void mouseEntered( MouseEvent event ) 51 { Invoked when user presses and releases mouse button Invoked when user presses mouse button Invoked when user releases mouse button Invoked when mouse cursor enters JFrame
49
2003 Prentice Hall, Inc. All rights reserved. Outline 49 MouseTracker.ja va Line 58 Line 66 Line 73 52 statusBar.setText( "Mouse entered at [" + event.getX() + 53 ", " + event.getY() + "]" ); 54 getContentPane().setBackground( Color.GREEN ); 55 } 56 57 // handle event when mouse exits area 58 public void mouseExited( MouseEvent event ) 59 { 60 statusBar.setText( "Mouse outside window" ); 61 getContentPane().setBackground( Color.WHITE ); 62 } 63 64 // MouseMotionListener event handlers 65 // handle event when user drags mouse with button pressed 66 public void mouseDragged( MouseEvent event ) 67 { 68 statusBar.setText( "Dragged at [" + event.getX() + 69 ", " + event.getY() + "]" ); 70 } 71 72 // handle event when user moves mouse 73 public void mouseMoved( MouseEvent event ) 74 { 75 statusBar.setText( "Moved at [" + event.getX() + 76 ", " + event.getY() + "]" ); 77 } 78 Invoked when mouse cursor exits JFrame Invoked when user drags mouse cursor Invoked when user moves mouse cursor
50
2003 Prentice Hall, Inc. All rights reserved. Outline 50 MouseTracker.ja va 79 public static void main( String args[] ) 80 { 81 MouseTracker application = new MouseTracker(); 82 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 83 } 84 85 } // end class MouseTracker
51
2003 Prentice Hall, Inc. All rights reserved. 51 13.13 Adapter Classes Interfaces require that every method be provided (e.g., MouseListener and MouseMotionListener) Adapter class –Implements interface –Provides default implementation of each interface method –Used when all methods in interface are not needed –Only write the methods you need
52
2003 Prentice Hall, Inc. All rights reserved. 52 Fig. 13.18Event-adapter classes and the interfaces they implement in package java.awt.event
53
2003 Prentice Hall, Inc. All rights reserved. Outline 53 Painter.java Line 22 1 // Fig. 13.19: Painter.java 2 // Using class MouseMotionAdapter. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class Painter extends JFrame { 8 private int pointCount = 0; 9 10 // array of 1000 java.awt.Point references 11 private Point points[] = new Point[ 1000 ]; 12 13 // set up GUI and register mouse event handler 14 public Painter() 15 { 16 super( "A simple paint program" ); 17 18 // create a label and place it in SOUTH of BorderLayout 19 getContentPane().add( new JLabel( "Drag the mouse to draw" ), 20 BorderLayout.SOUTH ); 21 22 addMouseMotionListener( 23 24 new MouseMotionAdapter() { // anonymous inner class 25 Register MouseMotionListener to listen for window’s mouse-motion events
54
2003 Prentice Hall, Inc. All rights reserved. Outline 54 Painter.java Line 27 Line 30 Line 51 26 // store drag coordinates and repaint 27 public void mouseDragged( MouseEvent event ) 28 { 29 if ( pointCount < points.length ) { 30 points[ pointCount ] = event.getPoint(); 31 ++pointCount; 32 repaint(); 33 } 34 } 35 36 } // end anonymous inner class 37 38 ); // end call to addMouseMotionListener 39 40 setSize( 300, 150 ); 41 setVisible( true ); 42 43 } // end Painter constructor 44 45 // draw oval in a 4-by-4 bounding box at specified location on window 46 public void paint( Graphics g ) 47 { 48 super.paint( g ); // clears drawing area 49 50 for ( int i = 0; i < points.length && points[ i ] != null; i++ ) 51 g.fillOval( points[ i ].x, points[ i ].y, 4, 4 ); 52 } Override method mouseDragged, but not method mouseMoved Store coordinates where mouse was dragged, then repaint JFrame Draw circle of diameter 4 where user dragged cursor
55
2003 Prentice Hall, Inc. All rights reserved. Outline 55 Painter.java 53 54 public static void main( String args[] ) 55 { 56 Painter application = new Painter(); 57 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 58 } 59 60 } // end class Painter
56
2003 Prentice Hall, Inc. All rights reserved. 56 13.14 Key Event Handling Interface KeyListener (KeyAdapter) –Handles key events Generated when keys on keyboard are pressed and released KeyEvent –Contains virtual key code that represents key
57
2003 Prentice Hall, Inc. All rights reserved. Outline 57 KeyDemo.java Line 23 1 // Fig. 13.22: KeyDemo.java 2 // Demonstrating keystroke events. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class KeyDemo extends JFrame implements KeyListener { 8 private String line1 = "", line2 = "", line3 = ""; 9 private JTextArea textArea; 10 11 // set up GUI 12 public KeyDemo() 13 { 14 super( "Demonstrating Keystroke Events" ); 15 16 // set up JTextArea 17 textArea = new JTextArea( 10, 15 ); 18 textArea.setText( "Press any key on the keyboard..." ); 19 textArea.setEnabled( false ); 20 textArea.setDisabledTextColor( Color.BLACK ); 21 getContentPane().add( textArea ); 22 23 addKeyListener( this ); // allow frame to process Key events 24 25 setSize( 350, 100 ); 26 setVisible( true ); Register JFrame for key events
58
2003 Prentice Hall, Inc. All rights reserved. Outline 58 KeyDemo.java Line 31 Line 33 and 40 Line 38 Line 45 27 28 } // end KeyDemo constructor 29 30 // handle press of any action key 31 public void keyPressed( KeyEvent event ) 32 { 33 line1 = "Key pressed: " + event.getKeyText( event.getKeyCode() ); 34 setLines2and3( event ); 35 } 36 37 // handle release of any key 38 public void keyReleased( KeyEvent event ) 39 { 40 line1 = "Key released: " + event.getKeyText( event.getKeyCode() ); 41 setLines2and3( event ); 42 } 43 44 // handle press of any non-action key 45 public void keyTyped( KeyEvent event ) 46 { 47 line1 = "Key typed: " + event.getKeyChar(); 48 setLines2and3( event ); 49 } 50 51 // set second and third lines of output 52 private void setLines2and3( KeyEvent event ) 53 { Called when user presses keyCalled when user releases keyCalled when user types key Return virtual key code
59
2003 Prentice Hall, Inc. All rights reserved. Outline 59 KeyDemo.java Line 57 54 line2 = "This key is " + ( event.isActionKey() ? "" : "not " ) + 55 "an action key"; 56 57 String temp = event.getKeyModifiersText( event.getModifiers() ); 58 59 line3 = "Modifier keys pressed: " + 60 ( temp.equals( "" ) ? "none" : temp ); 61 62 textArea.setText( line1 + "\n" + line2 + "\n" + line3 + "\n" ); 63 } 64 65 public static void main( String args[] ) 66 { 67 KeyDemo application = new KeyDemo(); 68 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 69 } 70 71 } // end class KeyDemo Determine if modifier keys (e.g., Alt, Ctrl, Meta and Shift) were used
60
2003 Prentice Hall, Inc. All rights reserved. Outline 60 KeyDemo.java
61
2003 Prentice Hall, Inc. All rights reserved. 61 13.15 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Process layout details –Programmer can concentrate on basic “look and feel” –Interface LayoutManager
62
2003 Prentice Hall, Inc. All rights reserved. 62 Fig. 13.23Layout managers
63
2003 Prentice Hall, Inc. All rights reserved. 63 13.15.1 FlowLayout FlowLayout –Most basic layout manager –GUI components placed in container from left to right, top to bottom (no size changes) –Components can be left, center, or right-aligned –layoutContainer, re-arrange the container now
64
2003 Prentice Hall, Inc. All rights reserved. Outline 64 FlowLayoutDemo. java Lines 17 and 21 1 // Fig. 13.24: FlowLayoutDemo.java 2 // Demonstrating FlowLayout alignments. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class FlowLayoutDemo extends JFrame { 8 private JButton leftButton, centerButton, rightButton; 9 private Container container; 10 private FlowLayout layout; 11 12 // set up GUI and register button listeners 13 public FlowLayoutDemo() 14 { 15 super( "FlowLayout Demo" ); 16 17 layout = new FlowLayout(); 18 19 // get content pane and set its layout 20 container = getContentPane(); 21 container.setLayout( layout ); 22 23 // set up leftButton and register listener 24 leftButton = new JButton( "Left" ); 25 container.add( leftButton ); Set layout as FlowLayout
65
2003 Prentice Hall, Inc. All rights reserved. Outline 65 FlowLayoutDemo. java Line 33 Line 53 26 leftButton.addActionListener( 27 28 new ActionListener() { // anonymous inner class 29 30 // process leftButton event 31 public void actionPerformed( ActionEvent event ) 32 { 33 layout.setAlignment( FlowLayout.LEFT ); 34 35 // realign attached components 36 layout.layoutContainer( container ); 37 } 38 39 } // end anonymous inner class 40 41 ); // end call to addActionListener 42 43 // set up centerButton and register listener 44 centerButton = new JButton( "Center" ); 45 container.add( centerButton ); 46 centerButton.addActionListener( 47 48 new ActionListener() { // anonymous inner class 49 50 // process centerButton event 51 public void actionPerformed( ActionEvent event ) 52 { 53 layout.setAlignment( FlowLayout.CENTER ); 54 When user presses left JButton, left align components When user presses center JButton, center components
66
2003 Prentice Hall, Inc. All rights reserved. Outline 66 FlowLayoutDemo. java Line 71 55 // realign attached components 56 layout.layoutContainer( container ); 57 } 58 } 59 ); 60 61 // set up rightButton and register listener 62 rightButton = new JButton( "Right" ); 63 container.add( rightButton ); 64 rightButton.addActionListener( 65 66 new ActionListener() { // anonymous inner class 67 68 // process rightButton event 69 public void actionPerformed( ActionEvent event ) 70 { 71 layout.setAlignment( FlowLayout.RIGHT ); 72 73 // realign attached components 74 layout.layoutContainer( container ); 75 } 76 } 77 ); 78 79 setSize( 300, 75 ); 80 setVisible( true ); When user presses right JButton, right components
67
2003 Prentice Hall, Inc. All rights reserved. Outline 67 FlowLayoutDemo. java 81 82 } // end constructor FlowLayoutDemo 83 84 public static void main( String args[] ) 85 { 86 FlowLayoutDemo application = new FlowLayoutDemo(); 87 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 88 } 89 90 } // end class FlowLayoutDemo Window has been resized to smaller width
68
2003 Prentice Hall, Inc. All rights reserved. 68 13.15.2 BorderLayout BorderLayout –Default layout manager for JFrame and Japplet content panes –Arranges components into five regions NORTH (top of container) expand horizontally SOUTH (bottom of container) expand horizontally EAST (left of container) expand vertically WEST (right of container) expand vertically CENTER (center of container) fills remaining space –More than five components by using panels
69
2003 Prentice Hall, Inc. All rights reserved. 69 13.15.2 BorderLayout –Constructors BorderLayout(horizgap, vertgap) BorderLayout() same as BorderLayout(1,1) –add method container.add(comp, BorderLayout.NORTH) container.add(comp) same as container.add(comp, BorderLayout.CENTER)
70
2003 Prentice Hall, Inc. All rights reserved. Outline 70 BorderLayoutDem o.java Lines 18 and 22 1 // Fig. 13.25: BorderLayoutDemo.java 2 // Demonstrating BorderLayout. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class BorderLayoutDemo extends JFrame implements ActionListener { 8 private JButton buttons[]; 9 private final String names[] = { "Hide North", "Hide South", 10 "Hide East", "Hide West", "Hide Center" }; 11 private BorderLayout layout; 12 13 // set up GUI and event handling 14 public BorderLayoutDemo() 15 { 16 super( "BorderLayout Demo" ); 17 18 layout = new BorderLayout( 5, 5 ); // 5 pixel gaps 19 20 // get content pane and set its layout 21 Container container = getContentPane(); 22 container.setLayout( layout ); 23 24 // instantiate button objects 25 buttons = new JButton[ names.length ]; 26 Set layout as BorderLayout with 5-pixel horizontal and vertical gaps
71
2003 Prentice Hall, Inc. All rights reserved. Outline 71 BorderLayoutDem o.java Lines 33-37 Lines 50 and 52 27 for ( int count = 0; count < names.length; count++ ) { 28 buttons[ count ] = new JButton( names[ count ] ); 29 buttons[ count ].addActionListener( this ); 30 } 31 32 // place buttons in BorderLayout; order not important 33 container.add( buttons[ 0 ], BorderLayout.NORTH ); 34 container.add( buttons[ 1 ], BorderLayout.SOUTH ); 35 container.add( buttons[ 2 ], BorderLayout.EAST ); 36 container.add( buttons[ 3 ], BorderLayout.WEST ); 37 container.add( buttons[ 4 ], BorderLayout.CENTER ); 38 39 setSize( 300, 200 ); 40 setVisible( true ); 41 42 } // end constructor BorderLayoutDemo 43 44 // handle button events 45 public void actionPerformed( ActionEvent event ) 46 { 47 for ( int count = 0; count < buttons.length; count++ ) 48 49 if ( event.getSource() == buttons[ count ] ) 50 buttons[ count ].setVisible( false ); 51 else 52 buttons[ count ].setVisible( true ); Place JButton s in regions specified by BorderLayout When JButton s are “invisible,” they are not displayed on screen, and BorderLayout rearranges
72
2003 Prentice Hall, Inc. All rights reserved. Outline 72 BorderLayoutDem o.java 53 54 // re-layout the content pane 55 layout.layoutContainer( getContentPane() ); 56 } 57 58 public static void main( String args[] ) 59 { 60 BorderLayoutDemo application = new BorderLayoutDemo(); 61 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 62 } 63 64 } // end class BorderLayoutDemo
73
2003 Prentice Hall, Inc. All rights reserved. Outline 73 BorderLayoutDem o.java
74
2003 Prentice Hall, Inc. All rights reserved. 74 13.15.3 GridLayout GridLayout –Divides container into grid of specified rows and columns –Components are added starting at top-left cell Proceed left-to-right until row is full Every cell is same size (components expanded or contracted to fit) –Constructors GridLayout(rows, cols, horizgap, vertgap) GridLayout(rows, cols)
75
2003 Prentice Hall, Inc. All rights reserved. Outline 75 GridLayoutDemo. java Line 21 Line 22 1 // Fig. 13.26: GridLayoutDemo.java 2 // Demonstrating GridLayout. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class GridLayoutDemo extends JFrame implements ActionListener { 8 private JButton buttons[]; 9 private final String names[] = 10 { "one", "two", "three", "four", "five", "six" }; 11 private boolean toggle = true; 12 private Container container; 13 private GridLayout grid1, grid2; 14 15 // set up GUI 16 public GridLayoutDemo() 17 { 18 super( "GridLayout Demo" ); 19 20 // set up layouts 21 grid1 = new GridLayout( 2, 3, 5, 5 ); 22 grid2 = new GridLayout( 3, 2 ); 23 24 // get content pane and set its layout 25 container = getContentPane(); 26 container.setLayout( grid1 ); Create GridLayout grid1 with 2 rows and 3 columns Create GridLayout grid2 with 3 rows and 2 columns
76
2003 Prentice Hall, Inc. All rights reserved. Outline 76 GridLayoutDemo. java Lines 46 and 48 27 28 // create and add buttons 29 buttons = new JButton[ names.length ]; 30 31 for ( int count = 0; count < names.length; count++ ) { 32 buttons[ count ] = new JButton( names[ count ] ); 33 buttons[ count ].addActionListener( this ); 34 container.add( buttons[ count ] ); 35 } 36 37 setSize( 300, 150 ); 38 setVisible( true ); 39 40 } // end constructor GridLayoutDemo 41 42 // handle button events by toggling between layouts 43 public void actionPerformed( ActionEvent event ) 44 { 45 if ( toggle ) 46 container.setLayout( grid2 ); 47 else 48 container.setLayout( grid1 ); 49 50 toggle = !toggle; // set toggle to opposite value 51 container.validate(); 52 } Toggle current GridLayout when user presses JButton
77
2003 Prentice Hall, Inc. All rights reserved. Outline 77 GridLayoutDemo. java 53 54 public static void main( String args[] ) 55 { 56 GridLayoutDemo application = new GridLayoutDemo(); 57 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 58 } 59 60 } // end class GridLayoutDemo
78
2003 Prentice Hall, Inc. All rights reserved. 78 13.16 Panels Panel –Helps organize components –Class JPanel is JComponent subclass –May have components (and other panels) added to them –Allow very complex design with panels used as components and even containing sub-panels
79
2003 Prentice Hall, Inc. All rights reserved. Outline 79 PanelDemo.java Line 23 1 // Fig. 13.27: PanelDemo.java 2 // Using a JPanel to help lay out components. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class PanelDemo extends JFrame { 8 private JPanel buttonPanel; 9 private JButton buttons[]; 10 11 // set up GUI 12 public PanelDemo() 13 { 14 super( "Panel Demo" ); 15 16 // get content pane 17 Container container = getContentPane(); 18 19 // create buttons array 20 buttons = new JButton[ 5 ]; 21 22 // set up panel and set its layout 23 buttonPanel = new JPanel(); 24 buttonPanel.setLayout( new GridLayout( 1, buttons.length ) ); 25 Create JPanel to hold JButton s
80
2003 Prentice Hall, Inc. All rights reserved. Outline 80 PanelDemo.java Line 29 Line 32 26 // create and add buttons 27 for ( int count = 0; count < buttons.length; count++ ) { 28 buttons[ count ] = new JButton( "Button " + ( count + 1 ) ); 29 buttonPanel.add( buttons[ count ] ); 30 } 31 32 container.add( buttonPanel, BorderLayout.SOUTH ); 33 34 setSize( 425, 150 ); 35 setVisible( true ); 36 37 } // end constructor PanelDemo 38 39 public static void main( String args[] ) 40 { 41 PanelDemo application = new PanelDemo(); 42 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 43 } 44 45 } // end class PanelDemo Add JButton s to JPanel Add JPanel to SOUTH region of Container
81
2003 Prentice Hall, Inc. All rights reserved. 81 14.2 JTextArea JTextArea –Area for manipulating multiple lines of text –Constructors JTextArea(string, rows, cols) JTextArea(rows, cols) –Since JTextArea s do not provide scrollbars, usually are placed in JScrollPane objects
82
2003 Prentice Hall, Inc. All rights reserved. Outline 82 TextAreaDemo.ja va Line 16 Lines 18-24 1 // Fig. 14.1: TextAreaDemo.java 2 // Copying selected text from one textarea to another. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class TextAreaDemo extends JFrame { 8 private JTextArea textArea1, textArea2; 9 private JButton copyButton; 10 11 // set up GUI 12 public TextAreaDemo() 13 { 14 super( "TextArea Demo" ); 15 16 Box box = Box.createHorizontalBox(); 17 18 String string = "This is a demo string to\n" + 19 "illustrate copying text\nfrom one textarea to \n" + 20 "another textarea using an\nexternal event\n"; 21 22 // set up textArea1 23 textArea1 = new JTextArea( string, 10, 15 ); 24 box.add( new JScrollPane( textArea1 ) ); 25 Create Box container for organizing GUI components Populate JTextArea with String, then add to Box
83
2003 Prentice Hall, Inc. All rights reserved. Outline 83 TextAreaDemo.ja va Line 36 Lines 44-45 26 // set up copyButton 27 copyButton = new JButton( "Copy >>>" ); 28 box.add( copyButton ); 29 copyButton.addActionListener( 30 31 new ActionListener() { // anonymous inner class 32 33 // set text in textArea2 to selected text from textArea1 34 public void actionPerformed( ActionEvent event ) 35 { 36 textArea2.setText( textArea1.getSelectedText() ); 37 } 38 39 } // end anonymous inner class 40 41 ); // end call to addActionListener 42 43 // set up textArea2 44 textArea2 = new JTextArea( 10, 15 ); 45 textArea2.setEditable( false ); 46 box.add( new JScrollPane( textArea2 ) ); 47 48 // add box to content pane 49 Container container = getContentPane(); 50 container.add( box ); // place in BorderLayout.CENTER 51 Instantiate uneditable JTextArea When user presses JButton, textArea1 ’s highlighted text is copied into textArea2
84
2003 Prentice Hall, Inc. All rights reserved. Outline 84 TextAreaDemo.ja va 52 setSize( 425, 200 ); 53 setVisible( true ); 54 55 } // end constructor TextAreaDemo 56 57 public static void main( String args[] ) 58 { 59 TextAreaDemo application = new TextAreaDemo(); 60 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 61 } 62 63 } // end class TextAreaDemo
85
2003 Prentice Hall, Inc. All rights reserved. 85 14.3 Creating a Customized Subclass of JPanel Extend JPanel to create new components –JPanel can be used as a dedicated drawing area Method paintComponent of class Jcomponent Usually called via repaint Similar to paint for Japplet and JFrame
86
2003 Prentice Hall, Inc. All rights reserved. Outline 86 CustomPanel.jav a Line 8 Line 11 Line 25 1 // Fig. 14.2: CustomPanel.java 2 // A customized JPanel class. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class CustomPanel extends JPanel { 7 public final static int CIRCLE = 1, SQUARE = 2; 8 private int shape; 9 10 // use shape to draw an oval or rectangle 11 public void paintComponent( Graphics g ) 12 { 13 super.paintComponent( g ); 14 15 if ( shape == CIRCLE ) 16 g.fillOval( 50, 10, 60, 60 ); 17 else if ( shape == SQUARE ) 18 g.fillRect( 50, 10, 60, 60 ); 19 } 20 21 // set shape value and repaint CustomPanel 22 public void draw( int shapeToDraw ) 23 { 24 shape = shapeToDraw; 25 repaint(); 26} 27 28 } // end class CustomPanel Store integer representing shape to draw Override method paintComponent of class JComponent to draw oval or rectangle Method repaint calls method paintComponent
87
2003 Prentice Hall, Inc. All rights reserved. Outline 87 CustomPanelTest.java Lines 18-19 1 // Fig. 14.3: CustomPanelTest.java 2 // Using a customized Panel object. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class CustomPanelTest extends JFrame { 8 private JPanel buttonPanel; 9 private CustomPanel myPanel; 10 private JButton circleButton, squareButton; 11 12 // set up GUI 13 public CustomPanelTest() 14 { 15 super( "CustomPanel Test" ); 16 17 // create custom drawing area 18 myPanel = new CustomPanel(); 19 myPanel.setBackground( Color.GREEN ); 20 21 // set up squareButton 22 squareButton = new JButton( "Square" ); 23 squareButton.addActionListener( 24 Instantiate CustomPanel object and set background to green
88
2003 Prentice Hall, Inc. All rights reserved. Outline 88 CustomPanelTest.java Line 30 Line 45 25 new ActionListener() { // anonymous inner class 26 27 // draw a square 28 public void actionPerformed( ActionEvent event ) 29 { 30 myPanel.draw( CustomPanel.SQUARE ); 31 } 32 33 } // end anonymous inner class 34 35 ); // end call to addActionListener 36 37 circleButton = new JButton( "Circle" ); 38 circleButton.addActionListener( 39 40 new ActionListener() { // anonymous inner class 41 42 // draw a circle 43 public void actionPerformed( ActionEvent event ) 44 { 45 myPanel.draw( CustomPanel.CIRCLE ); 46 } 47 48 } // end anonymous inner class 49 50 ); // end call to addActionListener 51 When user presses circleButton, draw circle on CustomPanel When user presses squareButton, draw square on CustomPanel
89
2003 Prentice Hall, Inc. All rights reserved. Outline 89 CustomPanelTest.java Line 54 52 // set up panel containing buttons 53 buttonPanel = new JPanel(); 54 buttonPanel.setLayout( new GridLayout( 1, 2 ) ); 55 buttonPanel.add( circleButton ); 56 buttonPanel.add( squareButton ); 57 58 // attach button panel & custom drawing area to content pane 59 Container container = getContentPane(); 60 container.add( myPanel, BorderLayout.CENTER ); 61 container.add( buttonPanel, BorderLayout.SOUTH ); 62 63 setSize( 300, 150 ); 64 setVisible( true ); 65 66 } // end constructor CustomPanelTest 67 68 public static void main( String args[] ) 69 { 70 CustomPanelTest application = new CustomPanelTest(); 71 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 72 } 73 74 } // end class CustomPanelTest Use GridLayout to organize buttons
90
2003 Prentice Hall, Inc. All rights reserved. 90 14.4 JPanel Subclass that Handles Its Own Events JPanel –Does not support conventional events e.g., events offered by buttons, text areas, etc. –Capable of recognizing lower-level events e.g., mouse events, key events, etc. –Self-contained panel Listens for its own mouse events –getPreferredSize often called to determine ideal size for a component ( JPanel size defaults to 10x10) –Anything drawn “off” the panel is clipped
91
2003 Prentice Hall, Inc. All rights reserved. Outline 91 SelfContainedPa nel.java Line 16 Lines 23-24 1 // Fig. 14.4: SelfContainedPanel.java 2 // A self-contained JPanel class that handles its own mouse events. 3 package com.deitel.jhtp5.ch14; 4 5 import java.awt.*; 6 import java.awt.event.*; 7 import javax.swing.*; 8 9 public class SelfContainedPanel extends JPanel { 10 private int x1, y1, x2, y2; 11 12 // set up mouse event handling for SelfContainedPanel 13 public SelfContainedPanel() 14 { 15 // set up mouse listener 16 addMouseListener( 17 18 new MouseAdapter() { // anonymous inner class 19 20 // handle mouse press event 21 public void mousePressed( MouseEvent event ) 22 { 23 x1 = event.getX(); 24 y1 = event.getY(); 25 } 26 Self-contained JPanel listens for MouseEvent s Save coordinates where user pressed mouse button
92
2003 Prentice Hall, Inc. All rights reserved. Outline 92 SelfContainedPa nel.java Lines 30-31 Line 40 Lines 47-48 27 // handle mouse release event 28 public void mouseReleased( MouseEvent event ) 29 { 30 x2 = event.getX(); 31 y2 = event.getY(); 32 repaint(); 33 } 34 35 } // end anonymous inner class 36 37 ); // end call to addMouseListener 38 39 // set up mouse motion listener 40 addMouseMotionListener( 41 42 new MouseMotionAdapter() { // anonymous inner class 43 44 // handle mouse drag event 45 public void mouseDragged( MouseEvent event ) 46 { 47 x2 = event.getX(); 48 y2 = event.getY(); 49 repaint(); 50 } 51 Save coordinates where user released mouse button, then repaint Self-contained JPanel listens for when mouse moves Save coordinates where user dragged mouse, then repaint
93
2003 Prentice Hall, Inc. All rights reserved. Outline 93 SelfContainedPa nel.java Lines 69-70 52 } // end anonymous inner class 53 54 ); // end call to addMouseMotionListener 55 56 } // end constructor SelfContainedPanel 57 58 // return preferred width and height of SelfContainedPanel 59 public Dimension getPreferredSize() 60 { 61 return new Dimension( 150, 100 ); 62 } 63 64 // paint an oval at the specified coordinates 65 public void paintComponent( Graphics g ) 66 { 67 super.paintComponent( g ); 68 69 g.drawOval( Math.min( x1, x2 ), Math.min( y1, y2 ), 70 Math.abs( x1 - x2 ), Math.abs( y1 - y2 ) ); 71 } 72 73 } // end class SelfContainedPanel Draw oval
94
2003 Prentice Hall, Inc. All rights reserved. Outline 94 SelfContainedPa nelTest.java Lines 17-18 1 // Fig. 14.5: SelfContainedPanelTest.java 2 // Creating a self-contained subclass of JPanel that processes 3 // its own mouse events. 4 import java.awt.*; 5 import java.awt.event.*; 6 import javax.swing.*; 7 8 import com.deitel.jhtp5.ch14.SelfContainedPanel; 9 10 public class SelfContainedPanelTest extends JFrame { 11 private SelfContainedPanel myPanel; 12 13 // set up GUI and mouse motion event handlers for application window 14 public SelfContainedPanelTest() 15 { 16 // set up a SelfContainedPanel 17 myPanel = new SelfContainedPanel(); 18 myPanel.setBackground( Color.YELLOW ); 19 20 Container container = getContentPane(); 21 container.setLayout( new FlowLayout() ); 22 container.add( myPanel ); 23 Instantiate SelfContaintedPanel object and set background to yellow
95
2003 Prentice Hall, Inc. All rights reserved. Outline 95 SelfContainedPa nelTest.java Line 25 Lines 30-41 24 // set up mouse motion event handling 25 addMouseMotionListener( 26 27 new MouseMotionListener() { // anonymous inner class 28 29 // handle mouse drag event 30 public void mouseDragged( MouseEvent event ) 31 { 32 setTitle( "Dragging: x=" + event.getX() + 33 "; y=" + event.getY() ); 34 } 35 36 // handle mouse move event 37 public void mouseMoved( MouseEvent event ) 38 { 39 setTitle( "Moving: x=" + event.getX() + 40 "; y=" + event.getY() ); 41 } 42 43 } // end anonymous inner class 44 45 ); // end call to addMouseMotionListener 46 47 setSize( 300, 200 ); 48 setVisible( true ); 49 50 } // end constructor SelfContainedPanelTest Register anonymous-inner-class object to handle mouse motion events Display String in title bar indicating x-y coordinate where mouse-motion event occurred
96
2003 Prentice Hall, Inc. All rights reserved. Outline 96 SelfContainedPa nelTest.java 51 52 public static void main( String args[] ) 53 { 54 SelfContainedPanelTest application = new SelfContainedPanelTest(); 55 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 56 } 57 58 } // end class SelfContainedPanelTest
97
2003 Prentice Hall, Inc. All rights reserved. 97 14.5 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) –paint draws on subclasses of JFrame and Japplet –paintComponent draws on subclasses of JComponent
98
2003 Prentice Hall, Inc. All rights reserved. 98 Fig. 14.6 JSlider component with horizontal orientation thumb tick mark
99
2003 Prentice Hall, Inc. All rights reserved. Outline 99 OvalPanel.java Line 14 Line 18 1 // Fig. 14.7: OvalPanel.java 2 // A customized JPanel class. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class OvalPanel extends JPanel { 7 private int diameter = 10; 8 9 // draw an oval of the specified diameter 10 public void paintComponent( Graphics g ) 11 { 12 super.paintComponent( g ); 13 14 g.fillOval( 10, 10, diameter, diameter ); 15 } 16 17 // validate and set diameter, then repaint 18 public void setDiameter( int newDiameter ) 19 { 20 // if diameter invalid, default to 10 21 diameter = ( newDiameter >= 0 ? newDiameter : 10 ); 22 repaint(); 23 } 24 Draw filled oval of diameter Set diameter, then repaint
100
2003 Prentice Hall, Inc. All rights reserved. Outline 100 OvalPanel.java 25 // used by layout manager to determine preferred size 26 public Dimension getPreferredSize() 27 { 28 return new Dimension( 200, 200 ); 29 } 30 31 // used by layout manager to determine minimum size 32 public Dimension getMinimumSize() 33 { 34 return getPreferredSize(); 35 } 36 37 } // end class OvalPanel
101
2003 Prentice Hall, Inc. All rights reserved. Outline 101 SliderDemo.java Lines 18-19 Lines 22-23 1 // Fig. 14.8: SliderDemo.java 2 // Using JSliders to size an oval. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 import javax.swing.event.*; 7 8 public class SliderDemo extends JFrame { 9 private JSlider diameterSlider; 10 private OvalPanel myPanel; 11 12 // set up GUI 13 public SliderDemo() 14 { 15 super( "Slider Demo" ); 16 17 // set up OvalPanel 18 myPanel = new OvalPanel(); 19 myPanel.setBackground( Color.YELLOW ); 20 21 // set up JSlider to control diameter value 22 diameterSlider = 23 new JSlider( SwingConstants.HORIZONTAL, 0, 200, 10 ); 24 diameterSlider.setMajorTickSpacing( 10 ); 25 diameterSlider.setPaintTicks( true ); 26 Instantiate OvalPanel object and set background to yellow Instantiate horizontal JSlider object with min. value of 0, max. value of 200 and initial thumb location at 10
102
2003 Prentice Hall, Inc. All rights reserved. Outline 102 SliderDemo.java Line 28 Line 35 27 // register JSlider event listener 28 diameterSlider.addChangeListener( 29 30 new ChangeListener() { // anonymous inner class 31 32 // handle change in slider value 33 public void stateChanged( ChangeEvent e ) 34 { 35 myPanel.setDiameter( diameterSlider.getValue() ); 36 } 37 38 } // end anonymous inner class 39 40 ); // end call to addChangeListener 41 42 // attach components to content pane 43 Container container = getContentPane(); 44 container.add( diameterSlider, BorderLayout.SOUTH ); 45 container.add( myPanel, BorderLayout.CENTER ); 46 47 setSize( 220, 270 ); 48 setVisible( true ); 49 50 } // end constructor SliderDemo 51 Register anonymous ChangeListener object to handle JSlider events When user accesses JSlider, set OvalPanel ’s diameter according to JSlider value
103
2003 Prentice Hall, Inc. All rights reserved. Outline 103 SliderDemo.java 52 public static void main( String args[] ) 53 { 54 SliderDemo application = new SliderDemo(); 55 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 56 } 57 58 } // end class SliderDemo
104
2003 Prentice Hall, Inc. All rights reserved. 104 14.7 Using Menus with Frames JMenu –Allows for performing actions without cluttering GUI –Can be used for JFrame or JApplet objects –Contained by menu bar JMenuBar (requires setJMenuBar ) –Comprised of menu items JMenuItem JCheckBoxMenuItem JRadioButtonMenuItem
105
2003 Prentice Hall, Inc. All rights reserved. 105 14.7 Using Menus with Frames JMenu –When menu is clicked, expands to show menu items –JMenuItem can be a JMenu to have a sub-menu –addActionListener for each menu item
106
2003 Prentice Hall, Inc. All rights reserved. Outline 106 MenuTest.java Line 22 1 // Fig. 14.9: MenuTest.java 2 // Demonstrating menus 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class MenuTest extends JFrame { 8 private final Color colorValues[] = 9 { Color.BLACK, Color.BLUE, Color.RED, Color.GREEN }; 10 private JRadioButtonMenuItem colorItems[], fonts[]; 11 private JCheckBoxMenuItem styleItems[]; 12 private JLabel displayLabel; 13 private ButtonGroup fontGroup, colorGroup; 14 private int style; 15 16 // set up GUI 17 public MenuTest() 18 { 19 super( "Using JMenus" ); 20 21 // set up File menu and its menu items 22 JMenu fileMenu = new JMenu( "File" ); 23 fileMenu.setMnemonic( 'F' ); 24 Instantiate File JMenu
107
2003 Prentice Hall, Inc. All rights reserved. Outline 107 MenuTest.java Line 26 Lines 36-38 Line 46 25 // set up About... menu item 26 JMenuItem aboutItem = new JMenuItem( "About..." ); 27 aboutItem.setMnemonic( 'A' ); 28 fileMenu.add( aboutItem ); 29 aboutItem.addActionListener( 30 31 new ActionListener() { // anonymous inner class 32 33 // 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", 38 "About", JOptionPane.PLAIN_MESSAGE ); 39 } 40 41 } // end anonymous inner class 42 43 ); // end call to addActionListener 44 45 // set up Exit menu item 46 JMenuItem exitItem = new JMenuItem( "Exit" ); 47 exitItem.setMnemonic( 'x' ); 48 fileMenu.add( exitItem ); 49 exitItem.addActionListener( 50 Instantiate About… JMenuItem to be placed in fileMenu When user selects About… JMenuItem, display message dialog with appropriate text Instantiate Exit JMenuItem to be placed in fileMenu
108
2003 Prentice Hall, Inc. All rights reserved. Outline 108 MenuTest.java Line 56 Line 64 Line 69 51 new ActionListener() { // anonymous inner class 52 53 // terminate application when user clicks exitItem 54 public void actionPerformed( ActionEvent event ) 55 { 56 System.exit( 0 ); 57 } 58 59 } // end anonymous inner class 60 61 ); // end call to addActionListener 62 63 // create menu bar and attach it to MenuTest window 64 JMenuBar bar = new JMenuBar(); 65 setJMenuBar( bar ); 66 bar.add( fileMenu ); 67 68 // create Format menu, its submenus and menu items 69 JMenu formatMenu = new JMenu( "Format" ); 70 formatMenu.setMnemonic( 'r' ); 71 72 // create Color submenu 73 String colors[] = { "Black", "Blue", "Red", "Green" }; 74 When user selects Exit JMenuItem, exit system Instantiate JMenuBar to contain JMenu s Instantiate Format JMenu
109
2003 Prentice Hall, Inc. All rights reserved. Outline 109 MenuTest.java Line 75 Lines 78-79 Line 96 75 JMenu colorMenu = new JMenu( "Color" ); 76 colorMenu.setMnemonic( 'C' ); 77 78 colorItems = new JRadioButtonMenuItem[ colors.length ]; 79 colorGroup = new ButtonGroup(); 80 ItemHandler itemHandler = new ItemHandler(); 81 82 // create color radio button menu items 83 for ( int count = 0; count < colors.length; count++ ) { 84 colorItems[ count ] = 85 new JRadioButtonMenuItem( colors[ count ] ); 86 colorMenu.add( colorItems[ count ] ); 87 colorGroup.add( colorItems[ count ] ); 88 colorItems[ count ].addActionListener( itemHandler ); 89 } 90 91 // select first Color menu item 92 colorItems[ 0 ].setSelected( true ); 93 94 // add format menu to menu bar 95 formatMenu.add( colorMenu ); 96 formatMenu.addSeparator(); 97 98 // create Font submenu 99 String fontNames[] = { "Serif", "Monospaced", "SansSerif" }; 100 Instantiate Color JMenu (submenu of Format JMenu ) Instantiate JRadioButtonMenuItem s for Color JMenu and ensure that only one menu item is selected at a time Separator places line between JMenuItem s
110
2003 Prentice Hall, Inc. All rights reserved. Outline 110 MenuTest.java Line 101 Lines 104-105 101 JMenu fontMenu = new JMenu( "Font" ); 102 fontMenu.setMnemonic( 'n' ); 103 104 fonts = new JRadioButtonMenuItem[ fontNames.length ]; 105 fontGroup = new ButtonGroup(); 106 107 // create Font radio button menu items 108 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 } 114 115 // select first Font menu item 116 fonts[ 0 ].setSelected( true ); 117 118 fontMenu.addSeparator(); 119 120 // set up style menu items 121 String styleNames[] = { "Bold", "Italic" }; 122 123 styleItems = new JCheckBoxMenuItem[ styleNames.length ]; 124 StyleHandler styleHandler = new StyleHandler(); 125 Instantiate Font JMenu (submenu of Format JMenu ) Instantiate JRadioButtonMenuItem s for Font JMenu and ensure that only one menu item is selected at a time
111
2003 Prentice Hall, Inc. All rights reserved. Outline 111 MenuTest.java 126 // create style checkbox menu items 127 for ( int count = 0; count < styleNames.length; count++ ) { 128 styleItems[ count ] = 129 new JCheckBoxMenuItem( styleNames[ count ] ); 130 fontMenu.add( styleItems[ count ] ); 131 styleItems[ count ].addItemListener( styleHandler ); 132 } 133 134 // put Font menu in Format menu 135 formatMenu.add( fontMenu ); 136 137 // add Format menu to menu bar 138 bar.add( formatMenu ); 139 140 // set up label to display text 141 displayLabel = new JLabel( "Sample Text", SwingConstants.CENTER ); 142 displayLabel.setForeground( colorValues[ 0 ] ); 143 displayLabel.setFont( new Font( "Serif", Font.PLAIN, 72 ) ); 144 145 getContentPane().setBackground( Color.CYAN ); 146 getContentPane().add( displayLabel, BorderLayout.CENTER ); 147 148 setSize( 500, 200 ); 149 setVisible( true ); 150 151 } // end constructor 152
112
2003 Prentice Hall, Inc. All rights reserved. Outline 112 MenuTest.java Line 163 Lines 168 and 176 Lines 169 and 177- 178 153 public static void main( String args[] ) 154 { 155 MenuTest application = new MenuTest(); 156 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 157 } 158 159 // inner class to handle action events from menu items 160 private class ItemHandler implements ActionListener { 161 162 // process color and font selections 163 public void actionPerformed( ActionEvent event ) 164 { 165 // process color selection 166 for ( int count = 0; count < colorItems.length; count++ ) 167 168 if ( colorItems[ count ].isSelected() ) { 169 displayLabel.setForeground( colorValues[ count ] ); 170 break; 171 } 172 173 // process font selection 174 for ( int count = 0; count < fonts.length; count++ ) 175 176 if ( event.getSource() == fonts[ count ] ) { 177 displayLabel.setFont( 178 new Font( fonts[ count ].getText(), style, 72 ) ); 179 break; 180 } Invoked when user selects JMenuItem Determine which font or color menu generated event Set font or color of JLabel, respectively
113
2003 Prentice Hall, Inc. All rights reserved. Outline 113 MenuTest.java Line 192 Lines 197-202 181 182 repaint(); 183 184 } // end method actionPerformed 185 186 } // end class ItemHandler 187 188 // inner class to handle item events from check box menu items 189 private class StyleHandler implements ItemListener { 190 191 // process font style selections 192 public void itemStateChanged( ItemEvent e ) 193 { 194 style = 0; 195 196 // check for bold selection 197 if ( styleItems[ 0 ].isSelected() ) 198 style += Font.BOLD; 199 200 // check for italic selection 201 if ( styleItems[ 1 ].isSelected() ) 202 style += Font.ITALIC; 203 204 displayLabel.setFont( 205 new Font( displayLabel.getFont().getName(), style, 72 ) ); Invoked when user selects JCheckBoxMenuItem Determine new font style
114
2003 Prentice Hall, Inc. All rights reserved. Outline 114 MenuTest.java 206 207 repaint(); 208 } 209 210 } // end class StyleHandler 211 212 } // end class MenuTest
115
2003 Prentice Hall, Inc. All rights reserved. 115 14.11 JTabbedPane Arranges GUI components into layers –One layer visible at a time –Access each layer via a tab –JTabbedPane –addTab(“title”, icon, component, “tool tip”)
116
2003 Prentice Hall, Inc. All rights reserved. Outline 116 JTabbedPaneDemo.java Line 14 Line20 Line 27 1 // Fig. 14.13: JTabbedPaneDemo.java 2 // Demonstrating JTabbedPane. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class JTabbedPaneDemo extends JFrame { 7 8 // set up GUI 9 public JTabbedPaneDemo() 10 { 11 super( "JTabbedPane Demo " ); 12 13 // create JTabbedPane 14 JTabbedPane tabbedPane = new JTabbedPane(); 15 16 // set up pane11 and add it to JTabbedPane 17 JLabel label1 = new JLabel( "panel one", SwingConstants.CENTER ); 18 JPanel panel1 = new JPanel(); 19 panel1.add( label1 ); 20 tabbedPane.addTab( "Tab One", null, panel1, "First Panel" ); 21 22 // set up panel2 and add it to JTabbedPane 23 JLabel label2 = new JLabel( "panel two", SwingConstants.CENTER ); 24 JPanel panel2 = new JPanel(); 25 panel2.setBackground( Color.YELLOW ); 26 panel2.add( label2 ); 27 tabbedPane.addTab( "Tab Two", null, panel2, "Second Panel" ); Create a JTabbedPane Add the first panelAdd the second panel
117
2003 Prentice Hall, Inc. All rights reserved. Outline 117 JTabbedPaneDemo.java Line 38 28 29 // set up panel3 and add it to JTabbedPane 30 JLabel label3 = new JLabel( "panel three" ); 31 JPanel panel3 = new JPanel(); 32 panel3.setLayout( new BorderLayout() ); 33 panel3.add( new JButton( "North" ), BorderLayout.NORTH ); 34 panel3.add( new JButton( "West" ), BorderLayout.WEST ); 35 panel3.add( new JButton( "East" ), BorderLayout.EAST ); 36 panel3.add( new JButton( "South" ), BorderLayout.SOUTH ); 37 panel3.add( label3, BorderLayout.CENTER ); 38 tabbedPane.addTab( "Tab Three", null, panel3, "Third Panel" ); 39 40 // add JTabbedPane to container 41 getContentPane().add( tabbedPane ); 42 43 setSize( 250, 200 ); 44 setVisible( true ); 45 46 } // end constructor 47 48 public static void main( String args[] ) 49 { 50 JTabbedPaneDemo tabbedPaneDemo = new JTabbedPaneDemo(); 51 tabbedPaneDemo.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 52 } 53 54 } // end class CardDeck Add the third panel
118
2003 Prentice Hall, Inc. All rights reserved. Outline 118 JTabbedPaneDemo.java
119
2003 Prentice Hall, Inc. All rights reserved. 119 14.14 Discovering Design Patterns: Design Patterns Used in Packages java.awt and javax.swing Continue design-patterns discussion –Design patterns associated with Java GUI components GUI components take advantage of design patterns
120
2003 Prentice Hall, Inc. All rights reserved. 120 14.14.1 Creational Design Patterns Factory Method design pattern –Suppose we design system that opens image from file Several image formats exist (e.g., GIF, JPEG, etc.) –Each image format has different structure Method createImage of class Component creates Image Two Image objects (one for GIF image, one for JPEG image) Method createImage uses parameter to determine proper Image subclass from which to instantiate Image object createImage( "image.gif" ); –Returns Image object with GIF data createImage( "image.jpg" ); –Returns Image object with JPEG data Method createImage is called a factory method –Determines subclass to instantiate object at run time
121
2003 Prentice Hall, Inc. All rights reserved. 121 14.14.2 Structural Design Patterns Adapter design pattern –Used with objects with incompatible interfaces Allows these objects to collaborate with each other Object’s interface adapts to another object’s interface –Similar to adapter for plug on electrical device European electrical sockets differ from those in United States American plug will not work with European socket Use adapter for plug –Class MouseAdapter Objects that generate MouseEvent s adapts to objects that handle MouseEvent s
122
2003 Prentice Hall, Inc. All rights reserved. 122 14.14.2 Structural Design Patterns Bridge design pattern (platform independence) –Design class Button for Windows and Macintosh systems Class contains button information (e.g., String label) Subclasses Win32Button and MacButton –Contain look-and-feel information Problem with this approach –Creating class ImageButton (subclass of Button ) Requires creating Win32ImageButton and MacImageButton Solution: –Separate abstraction (i.e., Button ) from implementation (i.e., Win32Button and MacButton ) –Button contains reference (bridge) to ButtonPeer Handles platform-specific implementations
123
2003 Prentice Hall, Inc. All rights reserved. 123 14.14.2 Structural Design Patterns Composite design pattern (organize and manipulate objects) –Organize components into hierarchical structures Each node represents component All nodes implement same interface –Polymorphism ensures clients traverse all nodes uniformly –Used by Swing components JPanel is JContainer subclass JPanel object can contain GUI component –JPanel remains unaware of component’s specific type
124
2003 Prentice Hall, Inc. All rights reserved. 124 Fig. 14.27Inheritance hierarchy for class JPanel javax.swing.JComponent javax.swing.JPanel java.awt.Container java.awt.Component
125
2003 Prentice Hall, Inc. All rights reserved. 125 14.14.3 Behavioral Design Patterns Chain-of-Responsibility design pattern –Determine object that handles message at run time –Three-line office-phone system First line handles call If first line is busy, second line handles call If second line is busy, third line handles call –Message sent through “chain” Each object in chain decides whether to handle message –If unable to handle message, that object sends message to next object in chain –Method processEvent of class Button Handles AWTEvent or sends to next object
126
2003 Prentice Hall, Inc. All rights reserved. 126 14.14.3 Behavioral Design Patterns Command design pattern –Applications provide several ways to perform same task Edit menu with menu items for cutting and copying text Toolbar and popup menus may offer same feature –Encapsulate functionality (command) in reusable object e.g., “cut text” functionality Functionality can then be added to menus, toolbars, etc. Developers code functionality only once
127
2003 Prentice Hall, Inc. All rights reserved. 127 14.14.3 Behavioral Design Patterns Observer design pattern –Design program for viewing bank-account information Class BankStatementData store bank-statement data Class TextDisplay displays data in text format Class BarGraphDisplay displays data in bar-graph format Class PieChartDisplay displays data in pie-chart format BankStatementData (subject) notifies Display classes (observers) to display data when it changes –Subject notifies observers when subject changes state Observers act in response to notification Promotes loose coupling –Used by class java.util.Observable class java.util.Observer
128
2003 Prentice Hall, Inc. All rights reserved. 128 Fig. 14.28Basis for the Observer design pattern notifies BankStatementData TextDisplay BarGraphDisplay PieChartDisplay Subject Observers
129
2003 Prentice Hall, Inc. All rights reserved. 129 14.14.3 Behavioral Design Patterns Strategy design pattern –Encapsulates algorithm –LayoutManager s are strategy objects Classes FlowLayout, BorderLayout, GridLayout, etc. –Implement interface LayoutManager Each class uses method addLayoutComponent –Each method implementation uses different algorithm FlowLayout adds components left-to-right BorderLayout adds components in five regions GridLayout adds components in specified grid Class Container has LayoutManager reference –Use method setLayout Select different layout manager at run time
130
2003 Prentice Hall, Inc. All rights reserved. 130 14.14.3 Behavioral Design Patterns Template Method design pattern –Objects share single algorithm defined in superclass –Consider Fig.14.28 Display objects use same algorithm to acquire and display data –Get statements from BankStatementData –Parse statements –Display statements Create superclass BankStatementDisplay –Provides methods that comprise algorithm –Subclasses override “display” method, because each subclass displays data differently
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.