capitulo 11

17
11 GUI Components: Part 1 OBJECTIVES In this chapter you will learn: The design principles of graphical user interfaces (GUIs). To build GUIs and handle events generated by user interactions with GUIs. To understand the packages containing GUI components, event-handling classes and interfaces. To create and manipulate buttons, labels, lists, text fields and panels. To handle mouse events and keyboard events. To use layout managers to arrange GUI components Do you think I can listen all day to such stuff? —Lewis Carroll Even a minor event in the life of a child is an event of that child’s world and thus a world event. —Gaston Bachelard You pays your money and you takes your choice. —Punch Guess if you can, choose if you dare. —Pierre Corneille

Upload: sony-luis-ramirez-herrera

Post on 30-Oct-2014

50 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: capitulo 11

11GUIComponents:Part 1

O B J E C T I V E SIn this chapter you will learn:

■ The design principles of graphical user interfaces (GUIs).

■ To build GUIs and handle events generated by userinteractions with GUIs.

■ To understand the packages containing GUIcomponents, event-handling classes and interfaces.

■ To create and manipulate buttons, labels, lists, text fieldsand panels.

■ To handle mouse events and keyboard events.

■ To use layout managers to arrange GUI components

Do you think I can listen allday to such stuff?—Lewis Carroll

Even a minor event in thelife of a child is an event ofthat child’s world and thus aworld event.—Gaston Bachelard

You pays your money andyou takes your choice.—Punch

Guess if you can, choose ifyou dare.—Pierre Corneille

Page 2: capitulo 11

2 Chapter 11 GUI Components: Part 1

Student Solution Exercises11.4 Fill in the blanks in each of the following statements:

a) The JTextField class directly extends class .ANS: JTextComponent.b) Container method attaches a GUI component to a container.ANS: add.c) Method is called when a mouse button is released (without moving the

mouse).ANS: mouseClicked.d) The class is used to create a group of JRadioButtons.ANS: ButtonGroup.

11.5 Determine whether each statement is true or false. If false, explain why.a) Only one layout manager can be used per Container.ANS: True.b) GUI components can be added to a Container in any order in a BorderLayout.ANS: True.c) JRadioButtons provide a series of mutually exclusive options (i.e., only one can be true

at a time).ANS: True.d) Graphics method setFont is used to set the font for text fields.ANS: False. Component method setFont is used.e) A JList displays a scrollbar if there are more items in the list than can be displayed.ANS: False. A JList never provides a scrollbar.f) A Mouse object has a method called mouseDragged.ANS: False. A Mouse object is not provided by Java.

11.7 Find any error(s) in each of the following and explain how to correct it (them).a) import javax.swing.JFrame

ANS: Semicolon is missing after the class name.b) panelObject.GridLayout( 8, 8 ); // set GridLayout

ANS: The GridLayout constructor cannot be used in this manner. The correct statementshould be:panelObject.getContentPane().setLayout( new GridLayout( 8, 8 ) );

c) container.setLayout( new FlowLayout( FlowLayout.DEFAULT ) );

ANS: Class FlowLayout does not contain static constant DEFAULT.d) container.add( eastButton, EAST ); // BorderLayout

ANS: EAST should be BorderLayout.EAST.

11.8 Create the following GUI. You do not have to provide any functionality.

Page 3: capitulo 11

Student Solution Exercises 3

ANS:

1 // Exercise 11.8 Solution: AlignFrame.java2 // Program creates a simple GUI.3 import java.awt.GridLayout;4 import java.awt.BorderLayout;5 import java.awt.FlowLayout;6 import javax.swing.JFrame;7 import javax.swing.JButton;8 import javax.swing.JTextField;9 import javax.swing.JCheckBox;

10 import javax.swing.JLabel;11 import javax.swing.JPanel;1213 public class AlignFrame extends JFrame14 {15 private JButton okJButton;16 private JButton cancelJButton;17 private JButton helpJButton;18 private JTextField xJTextField;19 private JTextField yJTextField;20 private JCheckBox snapJCheckBox;21 private JCheckBox showJCheckBox;22 private JLabel xJLabel;23 private JLabel yJLabel;24 private JPanel checkJPanel;25 private JPanel buttonJPanel;26 private JPanel fieldJPanel1;27 private JPanel fieldJPanel2;28 private JPanel fieldJPanel;2930 // constructor sets up GUI31 public AlignFrame()32 {33 super( "Align" );3435 // build checkJPanel36 snapJCheckBox = new JCheckBox( "Snap to Grid" );37 showJCheckBox = new JCheckBox( "Show Grid" );38 checkJPanel = new JPanel();39 checkJPanel.setLayout( new GridLayout( 2, 1 ) ); // use gridlayout40 checkJPanel.add( snapJCheckBox ); // add snap checkbox41 checkJPanel.add( showJCheckBox ); // add show checkbox4243 // build field panel144 xJLabel = new JLabel( "X: " );45 xJTextField = new JTextField( "8", 3 ); // set width of textfield46 fieldJPanel1 = new JPanel();47 fieldJPanel1.setLayout( new FlowLayout() ); // use flowlayout48 fieldJPanel1.add( xJLabel );49 fieldJPanel1.add( xJTextField );50

Page 4: capitulo 11

4 Chapter 11 GUI Components: Part 1

51 // build field panel252 yJLabel = new JLabel( "Y: " );53 yJTextField = new JTextField( "8", 3 ); // set width of textfield54 fieldJPanel2 = new JPanel();55 fieldJPanel2.setLayout( new FlowLayout() ); // use flowlayout56 fieldJPanel2.add( yJLabel );57 fieldJPanel2.add( yJTextField );5859 // build field panel60 fieldJPanel = new JPanel();61 fieldJPanel.setLayout( new BorderLayout() ); // use border layout62 fieldJPanel.add( fieldJPanel1, BorderLayout.NORTH );63 fieldJPanel.add( fieldJPanel2, BorderLayout.SOUTH );6465 // build button panel66 okJButton = new JButton( "Ok" );67 cancelJButton = new JButton( "Cancel" );68 helpJButton = new JButton( "Help" );69 buttonJPanel = new JPanel();70 buttonJPanel.setLayout( new GridLayout( 3, 1, 10, 5 ) );71 buttonJPanel.add( okJButton );72 buttonJPanel.add( cancelJButton );73 buttonJPanel.add( helpJButton );7475 // use flowlayout center-aligned and add components76 setLayout( new FlowLayout( FlowLayout.CENTER, 10, 5 ) );77 add( checkJPanel );78 add( fieldJPanel );79 add( buttonJPanel );80 } // end AlignFrame constructor81 } // end class AlignFrame

1 // Exercise 11.8 Solution: Align.java2 // Testing AlignFrame.3 import javax.swing.JFrame;45 public class Align6 {7 public static void main( String args[] )8 {9 AlignFrame alignFrame = new AlignFrame(); // create AlignFrame

10 alignFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );11 alignFrame.setSize( 300, 140 ); // set frame size12 alignFrame.setVisible( true ); // display frame13 } // end main14 } // end class Align

Page 5: capitulo 11

Student Solution Exercises 5

11.9 Create the following GUI. You do not have to provide any functionality.

ANS:

1 // Exercise 11.9 Solution: CalculatorFrame.java2 // Program creates a GUI that resembles a calculator.3 import java.awt.BorderLayout;4 import java.awt.GridLayout;5 import javax.swing.JFrame;6 import javax.swing.JButton;7 import javax.swing.JPanel;8 import javax.swing.JTextField;9

10 public class CalculatorFrame extends JFrame11 {12 private JButton keys[];13 private JPanel keyPadJPanel;14 private JTextField lcdJTextField;1516 // constructor sets up GUI17 public CalculatorFrame()18 {19 super( "Calculator" );2021 lcdJTextField = new JTextField( 20 ); // create lcdJTextField22 lcdJTextField.setEditable( true ); // allow user input2324 keys = new JButton[ 16 ]; // array keys contains 16 JButtons2526 // initialize all digit key buttons27 for ( int i = 0; i <= 9; i++ )28 keys[ i ] = new JButton( String.valueOf( i ) );2930 // initialize all function key buttons31 keys[ 10 ] = new JButton( "/" );32 keys[ 11 ] = new JButton( "*" );33 keys[ 12 ] = new JButton( "-" );34 keys[ 13 ] = new JButton( "+" );35 keys[ 14 ] = new JButton( "=" );36 keys[ 15 ] = new JButton( "." );3738 // set keyPadJPanel layout to grid layout39 keyPadJPanel = new JPanel();40 keyPadJPanel.setLayout( new GridLayout( 4, 4 ) );41

Page 6: capitulo 11

6 Chapter 11 GUI Components: Part 1

42 // add buttons to keyPadJPanel panel43 // 7, 8, 9, divide44 for ( int i = 7; i <= 10; i++ )45 keyPadJPanel.add( keys[ i ] );4647 // 4, 5, 648 for ( int i = 4; i <= 6; i++ )49 keyPadJPanel.add( keys[ i ] );5051 // multiply52 keyPadJPanel.add( keys[ 11 ] );5354 // 1, 2, 355 for ( int i = 1; i <= 3; i++ )56 keyPadJPanel.add( keys[ i ] );5758 // subtract59 keyPadJPanel.add( keys[ 12 ] );6061 // 062 keyPadJPanel.add( keys[ 0 ] );6364 // ., =, add65 for ( int i = 15; i >= 13; i-- )66 keyPadJPanel.add( keys[ i ] );6768 // add components to (default) border layout69 add( lcdJTextField, BorderLayout.NORTH );70 add( keyPadJPanel, BorderLayout.CENTER );71 } // end CalculatorFrame constructor72 } // end class CalculatorFrame

1 // Exercise 11.9 Solution: Calculator.java2 // Program creates a GUI that resembles a calculator.3 import javax.swing.JFrame;45 public class Calculator6 {7 public static void main( String args[] )8 {9 CalculatorFrame calculatorFrame = new CalculatorFrame();

10 calculatorFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );11 calculatorFrame.setSize( 200, 200 ); // set frame size12 calculatorFrame.setVisible( true ); // display frame13 } // end main14 } // end class Calculator

Page 7: capitulo 11

Student Solution Exercises 7

11.13 Enhance the temperature conversion application of Exercise 11.12 by adding the Kelvintemperature scale. The application should also allow the user to make conversions between any twoscales. Use the following formula for the conversion between Kelvin and Celsius (in addition to theformula in Exercise 11.12):

Kelvin = Celsius + 273.15

ANS:

1 // Exercise 11.13 Solution: ConvertFrame.java2 // Program converts temperatures.3 import java.awt.GridLayout;4 import java.awt.event.ActionListener;5 import java.awt.event.ActionEvent;6 import javax.swing.JFrame;7 import javax.swing.JPanel;8 import javax.swing.JLabel;9 import javax.swing.JTextField;

10 import javax.swing.JRadioButton;11 import javax.swing.ButtonGroup;1213 public class ConvertFrame extends JFrame14 {15 private JPanel fromJPanel;16 private JPanel toJPanel;17 private JLabel label1;18 private JLabel label2;19 private JLabel label3;20 private JLabel label4;21 private JTextField tempJTextField1;22 private JTextField tempJTextField2;23 private ButtonGroup fromButtonGroup;24 private ButtonGroup toButtonGroup;25 private JRadioButton celsiusToJRadioButton;26 private JRadioButton fahrenheitToJRadioButton;27 private JRadioButton kelvinToJRadioButton;28 private JRadioButton celsiusFromJRadioButton;29 private JRadioButton fahrenheitFromJRadioButton;30 private JRadioButton kelvinFromJRadioButton;3132 // constructor sets up GUI33 public ConvertFrame()34 {35 super( "Temperature Conversion" );3637 // create ButtonGroup for from JRadioButtons38 fahrenheitFromJRadioButton =39 new JRadioButton( "Fahrenheit", true );40 celsiusFromJRadioButton = new JRadioButton( "Celsius", false );41 kelvinFromJRadioButton = new JRadioButton( "Kelvin", false );42 fromButtonGroup = new ButtonGroup();43 fromButtonGroup.add( fahrenheitFromJRadioButton );44 fromButtonGroup.add( celsiusFromJRadioButton );45 fromButtonGroup.add( kelvinFromJRadioButton );46

Page 8: capitulo 11

8 Chapter 11 GUI Components: Part 1

47 // create ButtonGroup for to JRadioButtons48 fahrenheitToJRadioButton =49 new JRadioButton( "Fahrenheit", false );50 celsiusToJRadioButton = new JRadioButton( "Celsius", true );51 kelvinToJRadioButton = new JRadioButton( "Kelvin", false );52 toButtonGroup = new ButtonGroup();53 toButtonGroup.add( fahrenheitToJRadioButton );54 toButtonGroup.add( celsiusToJRadioButton );55 toButtonGroup.add( kelvinToJRadioButton );5657 // create from JPanel58 fromJPanel = new JPanel();59 fromJPanel.setLayout( new GridLayout( 1, 3 ) );60 fromJPanel.add( fahrenheitFromJRadioButton );61 fromJPanel.add( celsiusFromJRadioButton );62 fromJPanel.add( kelvinFromJRadioButton );6364 // create to JPanel65 toJPanel = new JPanel();66 toJPanel.setLayout( new GridLayout( 1, 3 ) );67 toJPanel.add( fahrenheitToJRadioButton );68 toJPanel.add( celsiusToJRadioButton );69 toJPanel.add( kelvinToJRadioButton );7071 // create labels72 label1 = new JLabel( "Convert from:" );73 label2 = new JLabel( "Convert to:" );74 label3 = new JLabel( "Enter Numeric Temperature: " );75 label4 = new JLabel( "Comparable Temperature is: " );7677 // create JTextField for getting temperature to be converted78 tempJTextField1 = new JTextField( 10 );79 tempJTextField1.addActionListener(8081 new ActionListener() // anonymous inner class82 {83 // perform conversions84 public void actionPerformed( ActionEvent event )85 {86 int convertTemp, temp;8788 temp = Integer.parseInt( ( ( JTextField )89 event.getSource() ).getText() );9091 // fahrenheit to celsius92 if ( fahrenheitFromJRadioButton.isSelected() &&93 celsiusToJRadioButton.isSelected() )94 {95 convertTemp = ( int ) ( 5.0f / 9.0f * ( temp - 32 ) );96 tempJTextField2.setText(97 String.valueOf( convertTemp ) );98 } // end if99 // fahrenheit to kelvin100 else if ( fahrenheitFromJRadioButton.isSelected() &&101 kelvinToJRadioButton.isSelected() )102 {

Page 9: capitulo 11

Student Solution Exercises 9

103 convertTemp = ( int )104 ( 5.0f / 9.0f * ( temp - 32 ) + 273 );105 tempJTextField2.setText(106 String.valueOf( convertTemp ) );107 } // end else if108 // celsius to fahrenheit109 else if ( celsiusFromJRadioButton.isSelected() &&110 fahrenheitToJRadioButton.isSelected() )111 {112 convertTemp = ( int ) ( 9.0f / 5.0f * temp + 32 );113 tempJTextField2.setText(114 String.valueOf( convertTemp ) );115 } // end else if116 // celsius to kelvin117 else if ( celsiusFromJRadioButton.isSelected() &&118 kelvinToJRadioButton.isSelected() )119 {120 convertTemp = temp + 273;121 tempJTextField2.setText(122 String.valueOf( convertTemp ) );123 } // end else if124 // kelvin to celsius125 else if ( kelvinFromJRadioButton.isSelected() &&126 celsiusToJRadioButton.isSelected() )127 {128 convertTemp = temp - 273;129 tempJTextField2.setText(130 String.valueOf( convertTemp ) );131 } // end else if132 // kelvin to fahrenheit133 else if ( kelvinFromJRadioButton.isSelected() &&134 fahrenheitToJRadioButton.isSelected() )135 {136 convertTemp =137 ( int ) ( 9.0f / 5.0f * ( temp - 273 ) + 32 );138 tempJTextField2.setText(139 String.valueOf( convertTemp ) );140 } // end else if141 } // end method actionPerformed142 } // end anonymous inner class143 ); // end call to addActionListener144145 // JTextField to display temperature after convertion146 tempJTextField2 = new JTextField( 10 );147 tempJTextField2.setEditable( false );148149 // add components to GUI150 setLayout( new GridLayout( 8, 1 ) );151 add( label1 );152 add( fromJPanel );153 add( label3 );154 add( tempJTextField1 );155 add( label2 );156 add( toJPanel );157 add( label4 );158 add( tempJTextField2 );

Page 10: capitulo 11

10 Chapter 11 GUI Components: Part 1

11.14 Write an application that displays events as they occur in a JTextArea. Provide a JComboBox

with a minimum of four items. The user should be able to choose an event to monitor from theJComboBox. When that particular event occurs, display information about the event in the JText-

Area. Use method toString on the event object to convert it to a string representation.ANS:

159 } // end ConvertFrame constructor160 } // end class ConvertFrame

1 // Exercise 11.13 Solution: Convert.java2 // Program converts temperatures.3 import javax.swing.JFrame;45 public class Convert6 {7 public static void main( String args[] )8 {9 ConvertFrame convertFrame = new ConvertFrame();

10 convertFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );11 convertFrame.setSize( 300, 220 ); // set frame size12 convertFrame.setVisible( true ); // display frame13 } // end main14 } // end class Convert

15 // Exercise 11.14 Solution: EventMonitorFrame.java16 // Program monitors events occurred.17 import java.awt.BorderLayout;18 import java.awt.event.ItemListener;19 import java.awt.event.ItemEvent;20 import java.awt.event.KeyEvent;21 import java.awt.event.KeyAdapter;22 import java.awt.event.MouseAdapter;23 import java.awt.event.MouseEvent;24 import java.awt.event.ActionListener;25 import java.awt.event.ActionEvent;26 import javax.swing.JFrame;27 import javax.swing.JComboBox;28 import javax.swing.JTextArea;29 import javax.swing.JButton;30 import javax.swing.JPanel;31 import javax.swing.JScrollPane;32

Page 11: capitulo 11

Student Solution Exercises 11

33 public class EventMonitorFrame extends JFrame34 {35 private JComboBox eventsComboBox;36 private JButton okButton;37 private JTextArea outputTextArea;38 private JPanel controlPanel;39 private String eventSelected = "ActionEvent";40 private String events[] =41 { "ActionEvent", "ItemEvent", "KeyEvent", "MouseEvent" };4243 // set up GUI44 public EventMonitorFrame()45 {46 super( "Monitoring Events" );47 setLayout( new BorderLayout() ); // set frame layout4849 // set up JComboBox and register its event handler50 eventsComboBox = new JComboBox( events );51 eventsComboBox.setMaximumRowCount( events.length );52 eventsComboBox.addItemListener( new ComboBoxHandler() );53 eventsComboBox.addKeyListener( new KeyHandler() );5455 // set up OK button and register its event handler56 okButton = new JButton( "OK" );57 okButton.addActionListener( new ActionHandler() );58 okButton.addKeyListener( new KeyHandler() );5960 // textarea to display events61 outputTextArea = new JTextArea( 8, 50 );62 outputTextArea.setLineWrap( true );63 outputTextArea.setWrapStyleWord( true );6465 // register mouse, key event handlers66 addMouseListener( new MouseHandler() );6768 controlPanel = new JPanel();69 controlPanel.add( eventsComboBox );70 controlPanel.add( okButton );71 add( controlPanel, BorderLayout.NORTH );72 add( new JScrollPane( outputTextArea ), BorderLayout.CENTER );73 } // end EventMonitorFrame constructor7475 // class handles combo box event76 private class ComboBoxHandler implements ItemListener77 {78 public void itemStateChanged( ItemEvent event )79 {80 eventSelected = ( String )eventsComboBox.getSelectedItem();81 if ( eventSelected.equals( "ItemEvent" ) )82 outputTextArea.append( String.format(83 "%s\n", event.toString() ) );84 } // end method itemStateChanged85 } // end inner class ComboBoxHandler86

Page 12: capitulo 11

12 Chapter 11 GUI Components: Part 1

87 // class handles mouse event88 private class MouseHandler extends MouseAdapter89 {90 public void mouseClicked( MouseEvent event )91 {92 eventSelected = ( String )eventsComboBox.getSelectedItem();93 if ( eventSelected.equals( "MouseEvent" ) )94 outputTextArea.append( String.format(95 "%s\n", event.toString() ) );96 } // end method mouseClicked97 } // end inner class MouseHandler9899 // class handles action event100 private class ActionHandler implements ActionListener101 {102 public void actionPerformed( ActionEvent event )103 {104 eventSelected = ( String )eventsComboBox.getSelectedItem();105 if ( eventSelected.equals( "ActionEvent" ) )106 outputTextArea.append( String.format(107 "%s\n", event.toString() ) );108 } // end method actionPerformed109 } // end inner class ActionHandler110111 // class handles key event112 private class KeyHandler extends KeyAdapter113 {114 public void keyTyped( KeyEvent event )115 {116 eventSelected = ( String )eventsComboBox.getSelectedItem();117 if ( eventSelected.equals( "KeyEvent" ) )118 outputTextArea.append( String.format(119 "%s\n", event.toString() ) );120 } // end method keyTyped121 } // end inner class KeyHandler122 } // end class EventMonitorFrame

1 // Exercises 11.14 Solution: EventMonitor.java2 // Program monitors events occurred.3 import javax.swing.JFrame;45 public class EventMonitor extends JFrame6 {7 public static void main( String[] args )8 {9 EventMonitorFrame application = new EventMonitorFrame();

10 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );11 application.setSize( 480, 300 ); // set size of window12 application.setVisible( true ); // show window13 } // end main14 } // end class EventMonitor

Page 13: capitulo 11

Student Solution Exercises 13

11.16 It is often useful to display the events that occur during the execution of an application. Thiscan help you understand when the events occur and how they are generated. Write an applicationthat enables the user to generate and process every event discussed in this chapter. The applicationshould provide methods from the ActionListener, ItemListener, ListSelectionListener,MouseListener, MouseMotionListener and KeyListener interfaces to display messages when theevents occur. Use method toString to convert the event objects received in each event handler intoa String that can be displayed. Method toString creates a String containing all the information inthe event object.

ANS:

1 // Exercise 11.16 Solution: EventsFrame.java2 // Program displays events that occur during execution.3 import java.awt.Color;4 import java.awt.BorderLayout;5 import java.awt.event.ActionListener;6 import java.awt.event.ActionEvent;7 import java.awt.event.ItemListener;8 import java.awt.event.ItemEvent;9 import java.awt.event.MouseListener;

10 import java.awt.event.MouseEvent;11 import java.awt.event.MouseMotionListener;12 import java.awt.event.KeyListener;13 import java.awt.event.KeyEvent;14 import javax.swing.JFrame;15 import javax.swing.JPanel;16 import javax.swing.JScrollPane;17 import javax.swing.JTextArea;18 import javax.swing.JComboBox;19 import javax.swing.JRadioButton;20 import javax.swing.JList;21 import javax.swing.JButton;22 import javax.swing.event.ListSelectionListener;23 import javax.swing.event.ListSelectionEvent;2425 public class EventsFrame extends JFrame implements ActionListener,26 ItemListener, MouseListener, MouseMotionListener,27 KeyListener, ListSelectionListener

Page 14: capitulo 11

14 Chapter 11 GUI Components: Part 1

28 {29 private JPanel panel1;30 private JScrollPane scrollPane;31 private JTextArea outputJTextArea;32 private JComboBox comboBox;33 private JRadioButton radioButton;34 private JList list;35 private JButton clearJButton;3637 private String names[] = {38 "Anteater", "Caterpillar", "Centipede", "Fire Fly" };3940 // set up GUI and register event handlers41 public EventsFrame()42 {43 super( "Events" );4445 // create GUI components46 outputJTextArea = new JTextArea( 10, 30 );47 outputJTextArea.setLineWrap( true );48 outputJTextArea.setEditable( false );49 outputJTextArea.setBackground( Color.WHITE );50 outputJTextArea.setForeground( Color.BLACK );5152 // add the output area to a scroll pane53 // so the user can scroll the output54 scrollPane = new JScrollPane( outputJTextArea );5556 // comboBox listens for item and key events57 comboBox = new JComboBox( names );58 comboBox.addItemListener( this );59 comboBox.addKeyListener( this );6061 // radioButton listens for action events62 radioButton = new JRadioButton( "Select Me", false );63 radioButton.addActionListener( this );6465 // list listens for list selection events66 list = new JList( names );67 list.addListSelectionListener( this );6869 // clear button for clearing the output area70 clearJButton = new JButton( "Clear" );71 clearJButton.addActionListener(7273 new ActionListener() // anonymous inner class74 {75 public void actionPerformed( ActionEvent event )76 {77 outputJTextArea.setText( "" );78 } // end method actionPerformed79 } // end anonymous inner class80 ); // end call to addActionListener81

Page 15: capitulo 11

Student Solution Exercises 15

82 // application listens to its own key and mouse events83 addMouseMotionListener( this );84 addMouseListener( this );8586 panel1 = new JPanel();87 panel1.add( comboBox );88 panel1.add( radioButton );89 panel1.add( list );90 panel1.add( clearJButton );9192 // add components to container93 setLayout( new BorderLayout() );94 add( scrollPane, BorderLayout.CENTER );95 add( panel1, BorderLayout.SOUTH );96 } // end EventsFrame constructor9798 // ActionListener event handlers99 public void actionPerformed( ActionEvent event )100 {101 display( "ActionEvent", event );102 } // end method actionPerformed103104 // ItemListener event handlers105 public void itemStateChanged( ItemEvent event )106 {107 display( "ItemEvent", event );108 } // end method itemStateChanged109110 // MouseListener event handlers111 public void mouseClicked( MouseEvent event )112 {113 display( "MouseEvent", event );114 } // end method mouseClicked115116 public void mouseEntered( MouseEvent event )117 {118 display( "MouseEvent", event );119 } // end method mouseEnered120121 public void mouseExited( MouseEvent event )122 {123 display( "MouseEvent", event );124 } // end method mouseExited125126 public void mousePressed( MouseEvent event )127 {128 display( "MouseEvent", event );129 } // end method mousePressed130131 public void mouseReleased( MouseEvent event )132 {133 display( "MouseEvent", event );134 } // end method mouseReleased135

Page 16: capitulo 11

16 Chapter 11 GUI Components: Part 1

136 // MouseMotionListener event handlers137 public void mouseDragged( MouseEvent event )138 {139 display( "MouseEvent", event );140 } // end method mouseDragged141142 public void mouseMoved( MouseEvent event )143 {144 display( "MouseEvent", event );145 } // end method mouseMoved146147 // KeyListener event handlers148 public void keyPressed( KeyEvent event )149 {150 display( "KeyEvent", event );151 } // end method keyPressed152153 public void keyReleased( KeyEvent event )154 {155 display( "KeyEvent", event );156 } // end method keyReleased157158 public void keyTyped( KeyEvent event )159 {160 display( "KeyEvent", event );161 } // end method keyTyped162163 // ListSelectionListener event handlers164 public void valueChanged( ListSelectionEvent event )165 {166 display( "ListSelectionEvent", event );167 } // end method valueChanged168169 // display event occurred to output170 public void display( String eventName, Object event )171 {172 outputJTextArea.append( String.format( "%s occurred\n%S\n\n",173 eventName, event.toString() ) );174 } // end method display175 } // end class EventsFrame

1 // Exercise 11.16 Solution: Events.java2 // Program displays events that occur during execution.3 import javax.swing.JFrame;45 public class Events6 {7 public static void main( String args[] )8 {9 EventsFrame eventsFrame = new EventsFrame(); // create EventsFrame

10 eventsFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );11 eventsFrame.setSize( 375, 325 ); // set frame size12 eventsFrame.setVisible( true ); // display frame13 } // end main14 } // end class Events

Page 17: capitulo 11

Student Solution Exercises 17