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

The Panels are now Classes

Same as previous applet except the JPanels are implemented as classes. This makes
the applet (class Prog6) readable and compact but requires communication between
the JPanel classes. Thus, the constructor for the TopPanel class contains references
to the applet and an object of the BotPanel class.

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

class TopPanel extends JPanel implements ActionListener {
   JButton a,b,c;
   BotPanel bp;
   Prog6Frame prog;

   public TopPanel (BotPanel bp, Prog6Frame prog) {
      this.bp = bp;
      this.prog = prog;
      setLayout(new GridLayout(1,3));
      add (a = new JButton("One,One"));
      add (b = new JButton("One,Two"));
      add (c = new JButton("Two,One"));
      a.addActionListener(this);
      b.addActionListener(this);
      c.addActionListener(this);
   }

   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == a) {
	 bp.d.setText("Now we are cooking");
	 prog.text.append("Now we are cooking\n");
      } else if (evt.getSource() == b) {
	 bp.e.setText("Wonderful!");
	 prog.text.append("Wonderful!\n");
      } else {
	 bp.f.setText(bp.d.getText());
	 prog.text.append("I do not know what to do\n");
      }
   }
}

class BotPanel extends JPanel {
   JTextField d,e,f;

   public BotPanel () {
      setLayout(new GridLayout(1,3));
      add (d = new JTextField("Nothing Yet"));
      add (e = new JTextField("Nothing Yet"));
      add (f = new JTextField("Nothing Yet"));
      e.setHorizontalAlignment(JTextField.CENTER);
   }
}

class Prog6Frame extends JFrame {
   BotPanel bp;
   JTextArea text;

   public Prog6Frame () {
      setLayout(new BorderLayout());
      add("South", bp = new BotPanel());
      add("North", new TopPanel(bp, this));
      add("Center", new JScrollPane(text = new JTextArea()));
   }
}

public class Prog6 extends Applet {
   public void init () {
      Prog6Frame pf = new Prog6Frame();
      pf.setSize(600,400);
      pf.setVisible(true);
   }
}