20-CS-694 Advanced Programming Techniques Spring 2012
Applets

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

       Previous     Next     Applet Source     All lectures

Listen to Button Press, Take Action

Same as previous applet except ActionListeners are added to the JButtons to
detect when a JButton is pressed and some text is displayed in a corresponding
JTextField when that happens. This is accomplished by implementing the
ActionListener interface required actionPerformed method.

import java.awt.*;          // For the GridLayout class
import java.awt.event.*;    // For ActionEvent, ActionListener class
import javax.swing.*;       // For the JButton, JTextField class
import java.applet.*;       // For the Applet class

class Prog4Frame extends JFrame implements ActionListener {
   JButton a,b,c;
   JTextField d,e,f;

   public Prog4Frame () {
      setLayout(new GridLayout(2,3));
      add (a = new JButton("One,One"));
      add (b = new JButton("One,Two"));
      add (c = new JButton("Two,One"));
      add (d = new JTextField("Nothing Yet"));
      add (e = new JTextField("Nothing Yet"));
      add (f = new JTextField("Nothing Yet"));
      e.setHorizontalAlignment(JTextField.CENTER);
      a.addActionListener(this);
      b.addActionListener(this);
      c.addActionListener(this);
   }

   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == a) {
	 d.setText("Now we are cooking");
      } else if (evt.getSource() == b) {
	 e.setText("Wonderful!");
      } else {
	 f.setText(d.getText());
      }
   }
}

public class Prog4 extends Applet {
   public void init () {
      Prog4Frame pf = new Prog4Frame();
      pf.setSize(600,100);
      pf.setVisible(true);
   }
}