Http web server - 282 Methods Chapter 6 The event handling in

282 Methods Chapter 6 The event handling in this example is similar to the event handling of the Craps applet in Fig. 6.9. Line 34 specifies that this applet should listen for events from the JTextFieldnumberField. Remember, the thiskeyword enables the applet to refer to itself. So, in line 34, the applet is telling numberFieldthat the applet should be notified (with a call to the applet s actionPerformedmethod) when an action event occurs in the numberField. In this example, the user presses the Enter key while typing in the numberField to generate the action event. A message is then sent to the applet (i.e., a method actionPerformed is called on the applet) indicating that the user of the program has interacted with one of the program s GUI components (numberField). Remember that the statement to register the applet as the numberField s listener will compile only if the applet class also implements ActionListener(line l2). 1 // Fig. 6.13: FibonacciTest.java 2 // Recursive fibonacci method 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class FibonacciTest extends JApplet 12 implements ActionListener { 13 14 JLabel numberLabel, resultLabel; 15 JTextField numberField, resultField; 16 17 // set up applet s GUI 18 public void init() 19 { 20 // obtain content pane and set its layout to FlowLayout 21 Container container = getContentPane(); 22 container.setLayout( new FlowLayout() ); 23 24 // create numberLabel and attach it to content pane 25 numberLabel = 26 new JLabel( “Enter an integer and press Enter” ); 27 container.add( numberLabel ); 28 29 // create numberField and attach it to content pane 30 numberField = new JTextField( 10 ); 31 container.add( numberField ); 32 33 // register this applet as numberField s ActionListener 34 numberField.addActionListener( this ); 35 36 // create resultLabel and attach it to content pane 37 resultLabel = new JLabel( “Fibonacci value is” ); 38 container.add( resultLabel ); 39 Fig. 6.13 Recursively generating Fibonacci numbers (part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Leave a Reply