20-CS-694 Advanced Programming Techniques Spring 2012
Frames

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

     Previous      Next      Applet Source      All lectures

Showing and Hiding JFrames

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

class FR extends JFrame implements ActionListener {
   JTextField text;
   String str = "First Time Opened";
   JButton save;

   // Constructor for frame
   public FR (String s) {
      Container cp = getContentPane();
      setTitle(s);
      cp.add("Center", text = new JTextField(str));
      cp.add("South", save = new JButton("Save"));
      save.addActionListener(this);
   }

   // This action only for buttons in this frame
   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == save) str = new String(text.getText());
   }
}

public class F extends Applet implements ActionListener {
   Thread runner;
   FR f1 = null, f2 = null;
   JButton b1, b2, b3, b4;

   public void init () {
      setLayout(new GridLayout(2,2,20,20));
      add(b1 = new JButton("Open D Window"));
      add(b2 = new JButton("Open H Window"));
      add(b3 = new JButton("Close D Window"));
      add(b4 = new JButton("Hide H Window"));
      b1.addActionListener(this);
      b2.addActionListener(this);
      b3.addActionListener(this);
      b4.addActionListener(this);

      f1 = new FR("This is a D Window");
      f1.setSize(200,100);
      f1.setVisible(true);

      f2 = new FR("This is an H Window");
      f2.setSize(200,100);
      f2.setVisible(true);
   }

   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == b1) {
         if (f1 == null) {
            f1 = new FR("This is a D Window");
            f1.setSize(200,100);
            f1.setVisible(true);
         }
      } else if (evt.getSource() == b2) {
         f2.setVisible(true);
      } else if (evt.getSource() == b3) {
         if (f1 != null) f1.hide();
         f1 = null;
      } else if (evt.getSource() == b4) f2.hide();
   }

   public void stop () {
      if (f1 != null) f1.dispose();
      if (f2 != null) f2.dispose();
   }
}