// Fibonacci // adapted from Deitel import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Fibonacci extends JApplet implements ActionListener { JLabel numberLabel; JTextField numberField; long fibonacciValue; public void init() { // obtain content pane and set its layout to FlowLayout Container container = getContentPane(); container.setLayout( new FlowLayout() ); // create numberLabel and attach it to content pane numberLabel = new JLabel( "Enter an integer and press Enter" ); container.add( numberLabel ); // create numberField and attach it to content pane numberField = new JTextField( 3 ); container.add( numberField ); // register this applet as numberField’s ActionListener numberField.addActionListener( this ); /* // create resultLabel and attach it to content pane resultLabel = new JLabel( "Fibonacci value is" ); container.add( resultLabel ); // create numberField, make it uneditable // and attach it to content pane resultField = new JTextField( 15 ); resultField.setEditable( false ); container.add( resultField ); */ } // obtain user input and call method fibonacci public void actionPerformed( ActionEvent event ) { int number; // obtain user’s input and convert to int number = Integer.parseInt( numberField.getText() ); showStatus( "Calculating ..." ); // calculate fibonacci value for number user input fibonacciValue = fibonacci( number ); // indicate processing complete and display result showStatus( "" + fibonacciValue ); // resultField.setText( Long.toString( fibonacciValue ) ); repaint(); } public void paint (Graphics g) { super.paint(g); int sqr; sqr = (int)Math.sqrt(fibonacciValue); g.fillRect(100,100,sqr,sqr); } public long fibonacci( int n ) { long f1=0, f2=1, fn=0; if (n == 0) return 0; if (n == 1) return 1; for (int i=2; i<=n; i++) { fn = f1 + f2; f1 = f2; f2 = fn; } return fn; } }