Home | Résumé | Courses | Contact | Useful Links | Favorite Links | USC - Homepage


Computer Science 1 - (CPTR151) - Lectures  


 Return to Courses | Course Content  



Computer Science 1 - (CPTR151)

by David Siguelnitzky, MIS; MTE

Lecture 13 - Version 1.2.1

Graphical User Interface Components - Part 1


Lecture 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.11 Multiple-Selection Lists
    13.12 Mouse Event Handling
    13.13 Adapter Classes
    13.14 Key Event Handling
    13.15 Layout Managers
            13.15.1 FlowLayout
            13.15.2 BorderLayout
            13.15.3 GridLayout
13.16 Panels



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, widgets, etc.)
                • User interacts with GUI component via mouse, keyboard, etc.

 


Browser window with GUI components

 


Some basic GUI components


 

13.2 Overview of Swing Components


    • Swing GUI components
        – Package javax.swing
        – Components originate from AWT (package java.awt)
        – Contain look and feel
                • Appearance and how users interact with program
        – Lightweight components
                • Written completely in Java
   • Class Component
        – Contains method paint for drawing Component onscreen
    • Class Container
        – Collection of related Component (Paint & Draw)
        – Contains method add for adding components
    • Class JComponent
        – For customizing look and feel
        – Shortcut keys (mnemonics)
        – Common event-handling capabilities

13.3 JLabel


    • Label
        – Provide text on GUI
        – Defined with class JLabel
        – Can display:
            • Single line of read-only text
            • Image
            • Text and image
 


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
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     }
50
51 } // end class LabelTest



        Line 8 Declare three JLabels
        Line 20 Create first JLabel with text “Label with text”
        Line 21 Tool tip is text that appears when user moves cursor over JLabel
        Lines 16-17 Create second JLabel with text to left of image
        Lines 32-37 Create third JLabel with text below image

 

 


13.4 Event Handling


    • GUIs are event driven
        – Generate events when user interacts with GUI
            • e.g., moving mouse, pressing button, typing in text field, etc.
            • Class java.awt.AWTEvent

 


Some event classes of package java.awt.event

 

13.4 Event Handling


    • Event-handling 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)



13.5 TextFields


    • JTextField
        – Single-line area in which user can enter text
    • JPasswordField
        – Extends JTextField
        – Hides characters that user enters
 


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
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     }
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: " + new String( passwordField.getPassword() );
78                             }
79              
80
81             JOptionPane.showMessageDialog( null, string );
82
83             } // end method actionPerformed
84
85     } // end private inner class TextFieldHandler
86
87 } // end class TextFieldTest

 



        Lines 8-9 Declare three JTextFields and one JPasswordField
        Line 20 First JTextField contains empty string
        Line 24 Second JTextField contains text “Enter text here”
        Line 30 Third JTextField contains uneditable text
        Line 34 JPasswordField contains text “Hidden text,” but text appears as series of asterisks (*)
        Lines 39-42 Register GUI components with TextFieldHandler (register for ActionEvents)
        Line 56 Every TextFieldHandler instance is an ActionListener
        Line 59 Method actionPerformed invoked when user presses Enter in GUI field

 

 

 






13.6 How Event Handling Works


    • Two open questions from Section 13.4
        – 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

 

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,which generates ActionEvents when user clicks button

 


Swing button hierarchy

 


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 );
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, "You pressed: " + event.getActionCommand() );
53      }
54   
55
56     } // end private inner class ButtonHandler
57
58 } // end class ButtonTest



        Line 8 Create two references to JButton instances
        Line 20 Instantiate JButton with text
        Lines 24-26 Instantiate JButton with image and rollover image
        Line 31 Instantiate ButtonHandler for JButton event handling
        Lines 32-33 Register JButtons to receive events from ButtonHandler
        Line 50 When user clicks JButton, ButtonHandler invokes method actionPerformed of all registered listeners

 

 

13.8 JCheckBox and JRadioButton


    • State buttons
        – On/Off or true/false values
        – Java provides three types
            • JToggleButton
            • JCheckBox
            • JRadioButton



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
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
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

 

        Line 9 Declare two JCheckBox instances
        Line 22 Set JTextField font to Serif, 14-point plain
        Lines 26 and 29 Instantiate JCheckBoxs for bolding and italicizing JTextField text, respectively
        Lines 34-35 Register JCheckBoxs to receive events from CheckBoxHandler
        Line 54 When user selects JCheckBox, CheckBoxHandler invokes method itemStateChanges of all registered listeners
        Line 65 Change JTextField font, depending on which JCheckBox was selected

 

 


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
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
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     }
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

 

        Lines 10-11 Declare four JRadioButton instances
        Line 12 JRadioButtons normally appear as a ButtonGroup
        Lines 28-35 Instantiate JRadioButtons for manipulating JTextField text font
        Lines 41-45 JRadioButtons belong to ButtonGroup
        Lines 55-60 Register JRadioButtons to receive events from RadioButtonHandler
        Line 83 When user selects JRadioButton, RadioButtonHandler invokes method itemStateChanged of all registered listeners
        Line 85 Set font corresponding to JRadioButton selected

 

 

13.9  JComboBox


    • JComboBox
        – List of items from which user can select
        – Also called a drop-down list


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[] =  { "bug1.gif", "bug2.gif",  "travelbug.gif", "buganim.gif" };
12         
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
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   
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


        Lines 27-28 Instantiate JComboBox to show three Strings from names array at a time
        Line 29 Register JComboBox to receive events from anonymous ItemListener
        Line 34 When user selects item in JComboBox, ItemListener invokes method itemStateChanged of all registered listeners
        Lines 38-39 Set appropriate Icon depending on user selection

 


13.10  JList


    • List
        – Series of items
        – Single-selection vs. multiple-selection
        – JList


 

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", "Dark Gray", "Gray", "Green",
12           "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" };
13          
14   
15       private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY,
16          Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED,
17          Color.WHITE, Color.YELLOW };
18          
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() );
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(colors[ colorList.getSelectedIndex() ] );
46                 }    
47                
48   
49             } // end anonymous inner class
50   
51          ); // end call to addListSelectionListener - line 38
52
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



    Line 30 Use colorNames array to populate JList
    Line 34 JList allows single selections
    Line 38 Register JList to receive events from anonymous ListSelectionListener
    Line 43 When user selects item in JList, ListSelectionListener invokes method valueChanged of all registered listeners
    Lines 45-46 Set appropriate background depending on user selection

 


13.11  Multiple-Selection Lists


    • Multiple-selection list
        – Select many items from Jlist
        – Allows continuous range selection
 


 

1      // Fig. 13.15: MultipleSelectionTest.java
2      // Copying items from one List to another.
3      import java.awt.*;
4      import java.awt.event.*;
5      import javax.swing.*;
6     
7      public class MultipleSelectionTest extends JFrame {
8         private JList colorList, copyList;
9         private JButton copyButton;
10       private final String colorNames[] = { "Black", "Blue", "Cyan",
11          "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange",
12          "Pink", "Red", "White", "Yellow" };
13   
14       // set up GUI
15       public MultipleSelectionTest()
16       {
17          super( "Multiple Selection Lists" );
18   
19          // get content pane and set its layout
20          Container container = getContentPane();
21          container.setLayout( new FlowLayout() );
22   
23          // set up JList colorList
24          colorList = new JList( colorNames );
25          colorList.setVisibleRowCount( 5 );
26          colorList.setSelectionMode(                        
27          ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
28          container.add( new JScrollPane( colorList ) );
29   
30          // create copy button and register its listener
31          copyButton = new JButton( "Copy >>>" );
32          copyButton.addActionListener(
33   
34             new ActionListener() {  // anonymous inner class
35   
36                // handle button event
37                public void actionPerformed( ActionEvent event )
38                {
39                   // place selected values in copyList
40                   copyList.setListData( colorList.getSelectedValues() );
41                }
42   
43             } // end anonymous inner class
44   
45          ); // end call to addActionListener
46   
47          container.add( copyButton );
48   
49          // set up JList copyList
50          copyList = new JList( );
51          copyList.setVisibleRowCount( 5 );
52          copyList.setFixedCellWidth( 100 );
53          copyList.setFixedCellHeight( 15 );
54          copyList.setSelectionMode(                       
55           ListSelectionModel.SINGLE_INTERVAL_SELECTION );
56          container.add( new JScrollPane( copyList ) );
57   
58          setSize( 300, 130 );
59          setVisible( true );
60   
61       } // end constructor MultipleSelectionTest
62   
63       public static void main( String args[] )
64       {
65          MultipleSelectionTest application = new MultipleSelectionTest();
66          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
67       }
68   
69    } // end class MultipleSelectionTest


    Lines 10-12 and 24 Use colorNames array to populate JList
    Lines 26-27 JList colorList allows multiple selections
    Line 40 When user presses JButton, JList copyList adds items that user selected from JList colorList
    Lines 54-55 JList colorList allows single selections

 



13.12  Mouse Event Handling

 

    • Event-listener interfaces for mouse events
        – MouseListener
        – MouseMotionListener
        – Listen for MouseEvents

 


Fig. 13.16 MouseListener and MouseMotionListener interface methods

 

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   
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() + ", " + event.getY() + "]" );
32             
33       }
34   
35       // handle event when mouse pressed
36       public void mousePressed( MouseEvent event )
37       {
38          statusBar.setText( "Pressed at [" + event.getX() + ", " + event.getY() + "]" );
39             
40       }
41   
42       // handle event when mouse released after dragging
43       public void mouseReleased( MouseEvent event )
44       {
45          statusBar.setText( "Released at [" + event.getX() + ", " + event.getY() + "]" );
46             
47       }
48   
49       // handle event when mouse enters area
50       public void mouseEntered( MouseEvent event )
51       {
52          statusBar.setText( "Mouse entered at [" + event.getX() + ", " + event.getY() + "]" );
53             
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() + ", " + event.getY() + "]" );
69             
70       }
71   
72       // handle event when user moves mouse
73       public void mouseMoved( MouseEvent event )
74       {
75          statusBar.setText( "Moved at [" + event.getX() + ", " + event.getY() + "]" );
76             
77       }
78   
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


    Lines 20-21 Register JFrame to receive mouse events
    Line 29 Invoked when user presses and releases mouse button
    Line 36 Invoked when user presses mouse button
    Line 43 Invoked when user releases mouse button after dragging mouse
    Line 50 Invoked when mouse cursor enters JFrame
    Line 58 Invoked when mouse cursor exits JFrame
    Line 66 Invoked when user drags mouse cursor
    Line 73 Invoked when user moves mouse cursor

 

 



13.13  Adapter Classes


    • Adapter class
        – Implements interface
        – Provides default implementation of each interface method
        – Used when all methods in interface is not needed

 

Fig. 13.18 Event-adapter classes and the interfaces they implement in package java.awt.event


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" ), BorderLayout.SOUTH );

20             

21   

22          addMouseMotionListener(

23   

24             new MouseMotionAdapter() {  // anonymous inner class

25

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 - Line 22

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       }

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

    Line 22 Register MouseMotionListener to listen for window’s mouse-motion events
    Line 27 Override method mouseDragged, but not method mouseMoved
    Line 30 Store coordinates where mouse was dragged, then repaint JFrame
    Line 51 Draw circle of diameter 4 where user dragged cursor

 


1      // Fig. 13.20: MouseDetails.java
2      // Demonstrating mouse clicks and distinguishing between mouse buttons.
3      import java.awt.*;
4      import java.awt.event.*;
5      import javax.swing.*;
6     
7      public class MouseDetails extends JFrame {
8         private int xPos, yPos;
9     
10       // set title bar String; register mouse listener; size and show window
11       public MouseDetails()
12       {
13          super( "Mouse clicks and buttons" );
14   
15          addMouseListener( new MouseClickHandler() );
16   
17          setSize( 350, 150 );
18          setVisible( true );
19       }
20   
21       // draw String at location where mouse was clicked