You are on page 1of 17

11

Do you think I can listen all day to such stuff?


Lewis Carroll

GUI Components: Part 1


OBJECTIVES
In this chapter you will learn:

Even a minor event in the life of a child is an event of that childs world and thus a world event.
Gaston Bachelard

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 elds and panels. To handle mouse events and keyboard events. To use layout managers to arrange GUI components

You pays your money and you takes your choice.


Punch

Guess if you can, choose if you dare.


Pierre Corneille

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 11 GUI Components: Part 1

Student Solution Exercises


11.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. class is used to create a group of JRadioButtons. d) The ANS: ButtonGroup. 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. 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 statement should be: c)
panelObject.getContentPane().setLayout( new GridLayout( 8, 8 ) ); container.setLayout( new FlowLayout( FlowLayout.DEFAULT ) ); container.add( eastButton, EAST ); // BorderLayout

11.5

11.7

d) 11.8

ANS: Class FlowLayout does not contain static constant DEFAULT. ANS: EAST should be BorderLayout.EAST.

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

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student Solution Exercises


ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

// Exercise 11.8 Solution: AlignFrame.java // Program creates a simple GUI. import java.awt.GridLayout; import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; public class AlignFrame extends JFrame { private JButton okJButton; private JButton cancelJButton; private JButton helpJButton; private JTextField xJTextField; private JTextField yJTextField; private JCheckBox snapJCheckBox; private JCheckBox showJCheckBox; private JLabel xJLabel; private JLabel yJLabel; private JPanel checkJPanel; private JPanel buttonJPanel; private JPanel fieldJPanel1; private JPanel fieldJPanel2; private JPanel fieldJPanel; // constructor sets up GUI public AlignFrame() { super( "Align" ); // build checkJPanel snapJCheckBox = new JCheckBox( "Snap to Grid" showJCheckBox = new JCheckBox( "Show Grid" ); checkJPanel = new JPanel(); checkJPanel.setLayout( new GridLayout( 2, 1 ) checkJPanel.add( snapJCheckBox ); // add snap checkJPanel.add( showJCheckBox ); // add show ); ); // use gridlayout checkbox checkbox

// build field panel1 xJLabel = new JLabel( "X: " ); xJTextField = new JTextField( "8", 3 ); // set width of textfield fieldJPanel1 = new JPanel(); fieldJPanel1.setLayout( new FlowLayout() ); // use flowlayout fieldJPanel1.add( xJLabel ); fieldJPanel1.add( xJTextField );

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

4
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Chapter 11 GUI Components: Part 1


// build field panel2 yJLabel = new JLabel( "Y: " ); yJTextField = new JTextField( "8", 3 ); // set width of textfield fieldJPanel2 = new JPanel(); fieldJPanel2.setLayout( new FlowLayout() ); // use flowlayout fieldJPanel2.add( yJLabel ); fieldJPanel2.add( yJTextField ); // build field panel fieldJPanel = new JPanel(); fieldJPanel.setLayout( new BorderLayout() ); // use border layout fieldJPanel.add( fieldJPanel1, BorderLayout.NORTH ); fieldJPanel.add( fieldJPanel2, BorderLayout.SOUTH ); // build button panel okJButton = new JButton( "Ok" ); cancelJButton = new JButton( "Cancel" ); helpJButton = new JButton( "Help" ); buttonJPanel = new JPanel(); buttonJPanel.setLayout( new GridLayout( 3, 1, 10, 5 ) ); buttonJPanel.add( okJButton ); buttonJPanel.add( cancelJButton ); buttonJPanel.add( helpJButton ); // use flowlayout center-aligned and add components setLayout( new FlowLayout( FlowLayout.CENTER, 10, 5 ) ); add( checkJPanel ); add( fieldJPanel ); add( buttonJPanel ); } // end AlignFrame constructor } // end class AlignFrame

// Exercise 11.8 Solution: Align.java // Testing AlignFrame. import javax.swing.JFrame; public class Align { public static void main( String args[] ) { AlignFrame alignFrame = new AlignFrame(); // create AlignFrame alignFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); alignFrame.setSize( 300, 140 ); // set frame size alignFrame.setVisible( true ); // display frame } // end main } // end class Align

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student Solution Exercises


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

ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

// Exercise 11.9 Solution: CalculatorFrame.java // Program creates a GUI that resembles a calculator. import java.awt.BorderLayout; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextField; public class CalculatorFrame extends JFrame { private JButton keys[]; private JPanel keyPadJPanel; private JTextField lcdJTextField; // constructor sets up GUI public CalculatorFrame() { super( "Calculator" ); lcdJTextField = new JTextField( 20 ); // create lcdJTextField lcdJTextField.setEditable( true ); // allow user input keys = new JButton[ 16 ]; // array keys contains 16 JButtons // initialize all digit key buttons for ( int i = 0; i <= 9; i++ ) keys[ i ] = new JButton( String.valueOf( i ) ); // initialize all function key buttons keys[ 10 ] = new JButton( "/" ); keys[ 11 ] = new JButton( "*" ); keys[ 12 ] = new JButton( "-" ); keys[ 13 ] = new JButton( "+" ); keys[ 14 ] = new JButton( "=" ); keys[ 15 ] = new JButton( "." ); // set keyPadJPanel layout to grid layout keyPadJPanel = new JPanel(); keyPadJPanel.setLayout( new GridLayout( 4, 4 ) );

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

6
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Chapter 11 GUI Components: Part 1


// add buttons to keyPadJPanel panel // 7, 8, 9, divide for ( int i = 7; i <= 10; i++ ) keyPadJPanel.add( keys[ i ] ); // 4, 5, 6 for ( int i = 4; i <= 6; i++ ) keyPadJPanel.add( keys[ i ] ); // multiply keyPadJPanel.add( keys[ 11 ] ); // 1, 2, 3 for ( int i = 1; i <= 3; i++ ) keyPadJPanel.add( keys[ i ] ); // subtract keyPadJPanel.add( keys[ 12 ] ); // 0 keyPadJPanel.add( keys[ 0 ] ); // ., =, add for ( int i = 15; i >= 13; i-- ) keyPadJPanel.add( keys[ i ] ); // add components to (default) border layout add( lcdJTextField, BorderLayout.NORTH ); add( keyPadJPanel, BorderLayout.CENTER ); } // end CalculatorFrame constructor } // end class CalculatorFrame

// Exercise 11.9 Solution: Calculator.java // Program creates a GUI that resembles a calculator. import javax.swing.JFrame; public class Calculator { public static void main( String args[] ) { CalculatorFrame calculatorFrame = new CalculatorFrame(); calculatorFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); calculatorFrame.setSize( 200, 200 ); // set frame size calculatorFrame.setVisible( true ); // display frame } // end main } // end class Calculator

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student Solution Exercises

11.13 Enhance the temperature conversion application of Exercise 11.12 by adding the Kelvin temperature scale. The application should also allow the user to make conversions between any two scales. Use the following formula for the conversion between Kelvin and Celsius (in addition to the formula in Exercise 11.12):
Kelvin = Celsius + 273.15 ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

// Exercise 11.13 Solution: ConvertFrame.java // Program converts temperatures. import java.awt.GridLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; public class ConvertFrame extends JFrame { private JPanel fromJPanel; private JPanel toJPanel; private JLabel label1; private JLabel label2; private JLabel label3; private JLabel label4; private JTextField tempJTextField1; private JTextField tempJTextField2; private ButtonGroup fromButtonGroup; private ButtonGroup toButtonGroup; private JRadioButton celsiusToJRadioButton; private JRadioButton fahrenheitToJRadioButton; private JRadioButton kelvinToJRadioButton; private JRadioButton celsiusFromJRadioButton; private JRadioButton fahrenheitFromJRadioButton; private JRadioButton kelvinFromJRadioButton; // constructor sets up GUI public ConvertFrame() { super( "Temperature Conversion" ); // create ButtonGroup for from JRadioButtons fahrenheitFromJRadioButton = new JRadioButton( "Fahrenheit", true ); celsiusFromJRadioButton = new JRadioButton( "Celsius", false ); kelvinFromJRadioButton = new JRadioButton( "Kelvin", false ); fromButtonGroup = new ButtonGroup(); fromButtonGroup.add( fahrenheitFromJRadioButton ); fromButtonGroup.add( celsiusFromJRadioButton ); fromButtonGroup.add( kelvinFromJRadioButton );

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

8
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

Chapter 11 GUI Components: Part 1


// create ButtonGroup for to JRadioButtons fahrenheitToJRadioButton = new JRadioButton( "Fahrenheit", false ); celsiusToJRadioButton = new JRadioButton( "Celsius", true ); kelvinToJRadioButton = new JRadioButton( "Kelvin", false ); toButtonGroup = new ButtonGroup(); toButtonGroup.add( fahrenheitToJRadioButton ); toButtonGroup.add( celsiusToJRadioButton ); toButtonGroup.add( kelvinToJRadioButton ); // create from JPanel fromJPanel = new JPanel(); fromJPanel.setLayout( new GridLayout( 1, 3 ) ); fromJPanel.add( fahrenheitFromJRadioButton ); fromJPanel.add( celsiusFromJRadioButton ); fromJPanel.add( kelvinFromJRadioButton ); // create to JPanel toJPanel = new JPanel(); toJPanel.setLayout( new GridLayout( 1, 3 ) ); toJPanel.add( fahrenheitToJRadioButton ); toJPanel.add( celsiusToJRadioButton ); toJPanel.add( kelvinToJRadioButton ); // create labels label1 = new JLabel( label2 = new JLabel( label3 = new JLabel( label4 = new JLabel( "Convert from:" ); "Convert to:" ); "Enter Numeric Temperature: " ); "Comparable Temperature is: " );

// create JTextField for getting temperature to be converted tempJTextField1 = new JTextField( 10 ); tempJTextField1.addActionListener( new ActionListener() // anonymous inner class { // perform conversions public void actionPerformed( ActionEvent event ) { int convertTemp, temp; temp = Integer.parseInt( ( ( JTextField ) event.getSource() ).getText() ); // fahrenheit to celsius if ( fahrenheitFromJRadioButton.isSelected() && celsiusToJRadioButton.isSelected() ) { convertTemp = ( int ) ( 5.0f / 9.0f * ( temp - 32 ) ); tempJTextField2.setText( String.valueOf( convertTemp ) ); } // end if // fahrenheit to kelvin else if ( fahrenheitFromJRadioButton.isSelected() && kelvinToJRadioButton.isSelected() ) {

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student Solution Exercises


103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
convertTemp = ( int ) ( 5.0f / 9.0f * ( temp - 32 ) + 273 ); tempJTextField2.setText( String.valueOf( convertTemp ) ); } // end else if // celsius to fahrenheit else if ( celsiusFromJRadioButton.isSelected() && fahrenheitToJRadioButton.isSelected() ) { convertTemp = ( int ) ( 9.0f / 5.0f * temp + 32 ); tempJTextField2.setText( String.valueOf( convertTemp ) ); } // end else if // celsius to kelvin else if ( celsiusFromJRadioButton.isSelected() && kelvinToJRadioButton.isSelected() ) { convertTemp = temp + 273; tempJTextField2.setText( String.valueOf( convertTemp ) ); } // end else if // kelvin to celsius else if ( kelvinFromJRadioButton.isSelected() && celsiusToJRadioButton.isSelected() ) { convertTemp = temp - 273; tempJTextField2.setText( String.valueOf( convertTemp ) ); } // end else if // kelvin to fahrenheit else if ( kelvinFromJRadioButton.isSelected() && fahrenheitToJRadioButton.isSelected() ) { convertTemp = ( int ) ( 9.0f / 5.0f * ( temp - 273 ) + 32 ); tempJTextField2.setText( String.valueOf( convertTemp ) ); } // end else if } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener // JTextField to display temperature after convertion tempJTextField2 = new JTextField( 10 ); tempJTextField2.setEditable( false ); // add components to GUI setLayout( new GridLayout( 8, 1 ) ); add( label1 ); add( fromJPanel ); add( label3 ); add( tempJTextField1 ); add( label2 ); add( toJPanel ); add( label4 ); add( tempJTextField2 );

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

10

Chapter 11 GUI Components: Part 1

159 } // end ConvertFrame constructor 160 } // end class ConvertFrame 1 2 3 4 5 6 7 8 9 10 11 12 13 14

// Exercise 11.13 Solution: Convert.java // Program converts temperatures. import javax.swing.JFrame; public class Convert { public static void main( String args[] ) { ConvertFrame convertFrame = new ConvertFrame(); convertFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); convertFrame.setSize( 300, 220 ); // set frame size convertFrame.setVisible( true ); // display frame } // end main } // end class Convert

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 the JComboBox. When that particular event occurs, display information about the event in the JTextArea. Use method toString on the event object to convert it to a string representation.
ANS:

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

// Exercise 11.14 Solution: EventMonitorFrame.java // Program monitors events occurred. import java.awt.BorderLayout; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyAdapter; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JComboBox; import javax.swing.JTextArea; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane;

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student Solution Exercises


33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
public class EventMonitorFrame extends JFrame { private JComboBox eventsComboBox; private JButton okButton; private JTextArea outputTextArea; private JPanel controlPanel; private String eventSelected = "ActionEvent"; private String events[] = { "ActionEvent", "ItemEvent", "KeyEvent", "MouseEvent" }; // set up GUI public EventMonitorFrame() { super( "Monitoring Events" ); setLayout( new BorderLayout() ); // set frame layout // set up JComboBox and register its event handler eventsComboBox = new JComboBox( events ); eventsComboBox.setMaximumRowCount( events.length ); eventsComboBox.addItemListener( new ComboBoxHandler() ); eventsComboBox.addKeyListener( new KeyHandler() ); // set up OK button and register its event handler okButton = new JButton( "OK" ); okButton.addActionListener( new ActionHandler() ); okButton.addKeyListener( new KeyHandler() ); // textarea to display events outputTextArea = new JTextArea( 8, 50 ); outputTextArea.setLineWrap( true ); outputTextArea.setWrapStyleWord( true ); // register mouse, key event handlers addMouseListener( new MouseHandler() ); controlPanel = new JPanel(); controlPanel.add( eventsComboBox ); controlPanel.add( okButton ); add( controlPanel, BorderLayout.NORTH ); add( new JScrollPane( outputTextArea ), BorderLayout.CENTER ); } // end EventMonitorFrame constructor // class handles combo box event private class ComboBoxHandler implements ItemListener { public void itemStateChanged( ItemEvent event ) { eventSelected = ( String )eventsComboBox.getSelectedItem(); if ( eventSelected.equals( "ItemEvent" ) ) outputTextArea.append( String.format( "%s\n", event.toString() ) ); } // end method itemStateChanged } // end inner class ComboBoxHandler

11

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

12

Chapter 11 GUI Components: Part 1

87 // class handles mouse event 88 private class MouseHandler extends MouseAdapter 89 { 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 mouseClicked 97 } // end inner class MouseHandler 98 99 // class handles action event 100 private class ActionHandler implements ActionListener 101 { 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 actionPerformed 109 } // end inner class ActionHandler 110 111 // class handles key event 112 private class KeyHandler extends KeyAdapter 113 { 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 keyTyped 121 } // end inner class KeyHandler 122 } // end class EventMonitorFrame 1 2 3 4 5 6 7 8 9 10 11 12 13 14

// Exercises 11.14 Solution: EventMonitor.java // Program monitors events occurred. import javax.swing.JFrame; public class EventMonitor extends JFrame { public static void main( String[] args ) { EventMonitorFrame application = new EventMonitorFrame(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.setSize( 480, 300 ); // set size of window application.setVisible( true ); // show window } // end main } // end class EventMonitor

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student Solution Exercises

13

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

// Exercise 11.16 Solution: EventsFrame.java // Program displays events that occur during execution. import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JComboBox; import javax.swing.JRadioButton; import javax.swing.JList; import javax.swing.JButton; import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionEvent; public class EventsFrame extends JFrame implements ActionListener, ItemListener, MouseListener, MouseMotionListener, KeyListener, ListSelectionListener

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

14
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
{

Chapter 11 GUI Components: Part 1

private private private private private private private

JPanel panel1; JScrollPane scrollPane; JTextArea outputJTextArea; JComboBox comboBox; JRadioButton radioButton; JList list; JButton clearJButton;

private String names[] = { "Anteater", "Caterpillar", "Centipede", "Fire Fly" }; // set up GUI and register event handlers public EventsFrame() { super( "Events" ); // create GUI components outputJTextArea = new JTextArea( 10, 30 ); outputJTextArea.setLineWrap( true ); outputJTextArea.setEditable( false ); outputJTextArea.setBackground( Color.WHITE ); outputJTextArea.setForeground( Color.BLACK ); // add the output area to a scroll pane // so the user can scroll the output scrollPane = new JScrollPane( outputJTextArea ); // comboBox listens for item and key events comboBox = new JComboBox( names ); comboBox.addItemListener( this ); comboBox.addKeyListener( this ); // radioButton listens for action events radioButton = new JRadioButton( "Select Me", false ); radioButton.addActionListener( this ); // list listens for list selection events list = new JList( names ); list.addListSelectionListener( this ); // clear button for clearing the output area clearJButton = new JButton( "Clear" ); clearJButton.addActionListener( new ActionListener() // anonymous inner class { public void actionPerformed( ActionEvent event ) { outputJTextArea.setText( "" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student Solution Exercises


82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
// application listens to its own key and mouse events addMouseMotionListener( this ); addMouseListener( this ); panel1 = new JPanel(); panel1.add( comboBox ); panel1.add( radioButton ); panel1.add( list ); panel1.add( clearJButton ); // add components to container setLayout( new BorderLayout() ); add( scrollPane, BorderLayout.CENTER ); add( panel1, BorderLayout.SOUTH ); } // end EventsFrame constructor // ActionListener event handlers public void actionPerformed( ActionEvent event ) { display( "ActionEvent", event ); } // end method actionPerformed // ItemListener event handlers public void itemStateChanged( ItemEvent event ) { display( "ItemEvent", event ); } // end method itemStateChanged // MouseListener event handlers public void mouseClicked( MouseEvent event ) { display( "MouseEvent", event ); } // end method mouseClicked public void mouseEntered( MouseEvent event ) { display( "MouseEvent", event ); } // end method mouseEnered public void mouseExited( MouseEvent event ) { display( "MouseEvent", event ); } // end method mouseExited public void mousePressed( MouseEvent event ) { display( "MouseEvent", event ); } // end method mousePressed public void mouseReleased( MouseEvent event ) { display( "MouseEvent", event ); } // end method mouseReleased

15

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

16

Chapter 11 GUI Components: Part 1

136 // MouseMotionListener event handlers 137 public void mouseDragged( MouseEvent event ) 138 { 139 display( "MouseEvent", event ); 140 } // end method mouseDragged 141 142 public void mouseMoved( MouseEvent event ) 143 { 144 display( "MouseEvent", event ); 145 } // end method mouseMoved 146 147 // KeyListener event handlers 148 public void keyPressed( KeyEvent event ) 149 { 150 display( "KeyEvent", event ); 151 } // end method keyPressed 152 153 public void keyReleased( KeyEvent event ) 154 { 155 display( "KeyEvent", event ); 156 } // end method keyReleased 157 158 public void keyTyped( KeyEvent event ) 159 { 160 display( "KeyEvent", event ); 161 } // end method keyTyped 162 163 // ListSelectionListener event handlers 164 public void valueChanged( ListSelectionEvent event ) 165 { 166 display( "ListSelectionEvent", event ); 167 } // end method valueChanged 168 169 // display event occurred to output 170 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 display 175 } // end class EventsFrame 1 2 3 4 5 6 7 8 9 10 11 12 13 14

// Exercise 11.16 Solution: Events.java // Program displays events that occur during execution. import javax.swing.JFrame; public class Events { public static void main( String args[] ) { EventsFrame eventsFrame = new EventsFrame(); // create EventsFrame eventsFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); eventsFrame.setSize( 375, 325 ); // set frame size eventsFrame.setVisible( true ); // display frame } // end main } // end class Events

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student Solution Exercises

17

2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

You might also like