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_5Frame {
   JFrame f;
   ActionListener l;
   JTextArea text;
   JButton go;
   int i;

   public java_5Frame () {
      f = new JFrame();
      l = new ActionListener () {
            public void actionPerformed (ActionEvent evt) {
               if (evt.getSource() == go) {
                  text.append(i+" ");
                  if ((i++ % 10) == 0) text.append("\n");
                  int p = text.getDocument().getLength();
                  text.setCaretPosition(p);
               }
            }
         };
      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);
      go.addActionListener(l);
      i = 1;
   }
}

public class java_5 
   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_5Frame jf = new java_5Frame();
      jf.f.setSize(450,300);
      jf.f.setVisible(true);
   }
}
 -  The usual way to achieve callback is through the use of inner classes. The code to the left achieves the same result as the code on the previous slide. The inner class solution exploits direct access to the widgets of the java_5Frame class.