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

JFrame Destroy and Hide

Click on the New Window button to add a window at the next level. Click on the Close Window button to destroy the current window.

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

class Assoc extends JFrame implements ActionListener {
   JButton a;

   // Constructor for frame   
   public Assoc () {
      setLayout(new BorderLayout());
      add("Center", new JLabel("Associated Window", JLabel.CENTER));
      add("South", a = new Button("Hide Window"));
      a.addActionListener(this);
   }
   
   // This action only for buttons in this frame
   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == a) setVisible(false);
   }
}   

class MyFrame extends JFrame implements ActionListener {
   JButton a, b;
   int level;

   // Constructor for frame
   public MyFrame (int n) {
      level = n;
      setTitle("Window Level "+level);
      setLayout(new BorderLayout());
      add("Center", new JLabel("Window level "+String.valueOf(level), JLabel.CENTER));
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(1,2,10,10));
      p.add(a = new JButton("New Window"));
      p.add(b = new JButton("Close Window"));
      add("South", p);
      a.addActionListener(this);
      b.addActionListener(this);
   }

   // This action only for buttons in this frame
   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == a) {
         MyFrame e = new MyFrame(level+1);
         e.setSize(300,120);
         e.setVisible(true);
      } else if (evt.getSource() == b) dispose();
   }
}

public class FrameTestApplet extends Applet implements ActionListener {
   JButton a, b;
   int level=0;
   Assoc assoc;

   public void init () {
      setLayout(new BorderLayout());
      add("Center", new JLabel("Root Window", JLabel.CENTER));
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(1,2,10,10));
      p.add(a = new JButton("New Window"));
      p.add(b = new JButton("Show Assoc Window"));
      add("South", p);
      a.addActionListener(this);
      b.addActionListener(this);
      assoc = new Assoc();
      assoc.setSize(300,120);
   }

   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == a) {
         MyFrame e = new MyFrame(level+1);
         e.setSize(300,120);
         e.setVisible(true);
      } else if (evt.getSource() == b) assoc.setVisible(true);
   }
}