Professional Documents
Culture Documents
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
2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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.
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
// 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.
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
// 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.
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
// 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.
2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10
// 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.
11
2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
12
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.
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
{
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.
15
2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
16
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.
17
2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.