20-CS-694 Advanced Programming Techniques Spring 2012
Inheritance

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

   public java_3Frame () {
      f = new JFrame();
      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(this);
      i = 1;
   }

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

public class java_3 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_3Frame jf = new java_3Frame();
      jf.f.setSize(450,300);
      jf.f.setVisible(true);
   }
}
 -  But a class can use services of another class by creating an object of that class and then by invoking methods on that object. This is done to the left with JFrame. The change from the previous slide is to eliminate extends from java_3Frame, add JFrame f, and then add f. where the services of a JFrame are required.