20-CS-694 Advanced Programming Techniques Spring 2012
Class services

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

    Prev     Next     All lectures        Code    

Use Services Provided by Other Classes

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;

class java_4Frame {
   JFrame f;
   AListener l;
   JTextArea text;
   JButton go;
   int i;

   public java_4Frame () {
      f = new JFrame();
      l = new AListener(this);
      f.setLayout(new BorderLayout());
      f.add("Center", 
            new JScrollPane(text=new JTextArea()));
      JPanel p = new JPanel();
      p.setLayout(new FlowLayout());
      p.add(go = new JButton("Run it"));
      f.add("South", p);
      l.addAListener(go);
      i = 1;
   }

   public void action (Object evt) {
      if (((ActionEvent)evt).getSource() == go) {
         text.append(i+" ");
         if ((i++ % 10) == 0) text.append("\n");
         int p = text.getDocument().getLength();
         text.setCaretPosition(p);
      }
   }
}

public class java_4 
   extends Applet implements ActionListener {
   JButton go;

   public void init () {
      setLayout(new FlowLayout());
      add(go = new JButton("Applet"));
      go.addActionListener(this);
   }

   public void actionPerformed (ActionEvent evt) {
      java_4Frame jf = new java_4Frame();
      jf.f.setSize(450,300);
      jf.f.setVisible(true);
   }
}

class AListener implements ActionListener {
   JButton obj;
   java_4Frame cls;

   public AListener (java_4Frame cls) { 
      this.cls = cls; 
   }

   public void addAListener (JButton obj) { 
      this.obj = obj;
      obj.addActionListener(this);
   }

   public void actionPerformed (ActionEvent evt) {
      cls.action(evt);
   }
}
 -  In the previous example it is OK to create a JFrame object to provide JFrame services instead of inheriting from JFrame because the JFrame object does not need to send results back to java_3Frame. However, in numerous cases a callback is necessary. For example, when the JButton is clicked, the event it causes must be sent back to java_3Frame to be processed, in that case by actionPerformed. The ActionListener interface provides a guarantee that the appropriate method will be available to receive this callback. But even this is not necessary as the code to the left shows. Class java_4Frame neither extends a class nor implements an interface yet it acts on a button press and it displays a window. To achieve this another class called AListener is written. An object l of this class is instantiated in the constructor of java_4Frame in the same way that JFrame object f is except with this as an argument. Then l.addAlistener(go) is invoked instead of go.addActionListener(this) as in the previous code example. This time java_4Frame provides the guarantee that a callback procedure, namely action, will be available to the AListener class.