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

Bolt Widgets onto Panels, Panels onto Applet

Same as previous applet except the JButtons are added to a JPanel which is added
to the North section of a BorderLayout, the JTextFields are added to a JPanel which
is added to the South section, and a JTextArea is added to the Center section. When
a JButton is pressed, some text is displayed in a JTextField and also in the JTextArea.

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 Prog5Frame extends JFrame implements ActionListener {
   JButton a,b,c;
   JTextField d,e,f;
   JTextArea text;

   public Prog5Frame () {
      setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(1,3));
      p.add (a = new JButton("One,One"));
      p.add (b = new JButton("One,Two"));
      p.add (c = new JButton("Two,One"));
      add("North",p);

      p = new JPanel();
      p.setLayout(new GridLayout(1,3));
      p.add (d = new JTextField("Nothing Yet"));
      p.add (e = new JTextField("Nothing Yet"));
      p.add (f = new JTextField("Nothing Yet"));
      add("South",p);

      add("Center", new JScrollPane(text = new JTextArea()));

      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");
         text.append("Now we are cooking\n");
      } else if (evt.getSource() == b) {
         e.setText("Wonderful!");
         text.append("Wonderful!\n");
      } else {
         f.setText(d.getText());
         text.append("I do not know what to do\n");
      }
   }
}

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