// file: Lesson2.java // type: Java code // note: Handling buttons and fields // author: Gregory C. Walsh // date: 3.9.1999 import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.*; import java.applet.Applet; public class Lesson2 extends Applet implements ActionListener{ TextField input; Label output; Button zap, go, stop, reload; Font f; int ammo; public void init () { // Initialize amount of Ammo. This is // a parameter which may be passed from the // html code which calls the applet. // The default value is 6 String buffer = getParameter("ammo"); if(buffer == null) { ammo = 6; } else { ammo = (int) Integer.valueOf(buffer).intValue(); } // Pick Font for GUI objects f = new Font("TimesRoman",Font.PLAIN,16); // First generate the GUI objects and set fonts on gui's.... output = new Label( "Ammunition = " + ammo,Label.CENTER); output.setFont(f); input = new TextField( 20 ); input.setFont(f); zap = new Button( "Zap!"); zap.setFont(f); go = new Button("Go"); go.setFont(f); stop = new Button("Stop"); stop.setFont(f); reload = new Button("Reload"); reload.setFont(f); // Connect GUI components to actionlistener .... zap.addActionListener(this); go.addActionListener(this); stop.addActionListener(this); reload.addActionListener(this); // Now add the components to the Applet add(output); add(zap); add(go); add(stop); add(reload); add(input); // Configure the initial button state go.setEnabled(true); stop.setEnabled(false); } // Actionlistener for the buttons ..... public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if( (command == "Zap!") && (stop.isEnabled()) ) { if(ammo>0) { ammo--; Toolkit.getDefaultToolkit().beep(); output.setText("Ammo: " + ammo); input.setText(input.getText() + " Zap!!"); if(ammo == 0) output.setText("Empty!"); } else output.setText("Out of ammo!"); } if(command == "Go") { showStatus(" ... Zap ready to go!"); go.setEnabled(false); output.setText("Ammo: " + ammo); stop.setEnabled(true); } if(command == "Reload") { showStatus(" ... Zap on safety!"); go.setEnabled(true); stop.setEnabled(false); output.setText("Ammo reloaded"); ammo = 6; input.setText(""); } if(command == "Stop") { showStatus(" ... Zap on safety!"); go.setEnabled(true); stop.setEnabled(false); input.setText(""); } return; } }