import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Label; import java.awt.Choice; import java.awt.Panel; import java.awt.TextField; import java.awt.TextArea; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; /* * Applet GUI for Greatest Common Divisor functions. */ public class GCDApplet extends Applet implements KeyListener{ /* * The init method builds the user interface. It is also responsible * for initializing the event handling. */ // GUI elements Choice calc = new Choice(); TextField a_value = new TextField(12); TextField b_value = new TextField(12); TextArea result_area = new TextArea("", 4, 30, TextArea.SCROLLBARS_VERTICAL_ONLY); public void init(){ setLayout(new BorderLayout()); Panel north = new Panel(); add(north, BorderLayout.NORTH); // The north panel should start with a message to the user. north.add(new Label("a: ")); north.add(a_value); a_value.addKeyListener(this); north.add(new Label("b: ")); north.add(b_value); b_value.addKeyListener(this); // Build the function menu and add it to the north panel. calc.add("Recursive calulation"); calc.add("Iterating calculation"); north.add(calc); // Add the text area to the center panel. We also turn off // editing so that the user can read from, but not write to the area. result_area.setEditable(false); add(result_area, BorderLayout.CENTER); } //init public void keyPressed(KeyEvent event) {} public void keyTyped(KeyEvent event) {} public void keyReleased(KeyEvent event){ if((event.getKeyCode() == KeyEvent.VK_ENTER) && ((event.getSource() == a_value) || (event.getSource() == b_value))){ //Initialize long a = 0, b = 0; // Get a and b value from the prompt try{ a = Long.valueOf(a_value.getText()).longValue(); b = Long.valueOf(b_value.getText()).longValue(); }catch(Exception e){}; // Get calculation method, compute gcd and write reslt to text area. result_area.append("GCD(" + a + ", " + b + ") = " + GCD.gcd(a, b, (calc.getSelectedIndex() == 0) ? GCD.GCD_REC : GCD.GCD_IT) + "\n"); } //if } //keyReleased } //class GCDApplet