by Java Q&a Experts

Use the setState(int state) method to iconify child windows (July 6, 1999)

news
Jul 6, 19992 mins

The JavaWorld experts answer your most pressing Java questions -- every week

Q: I use JDK 1.2 on an NT box. When my Java application runs, it pops up a root window from which a user can make selections that may cause child windows to be launch. When the user iconifies the root window — turns it into an icon — I would like to programmatically iconify the child window. I cannot find a method to do this. Can you help?

A: The setState(int state) method in class java.awt.Frame can accomplish this task. Call setState(Frame.ICONIFIED) to programmatically minimize a frame, and call setState(Frame.NORMAL) to restore it.

The following sample program creates a frame containing a button. Clicking this button causes a new child frame to be created. When the main frame is minimized, all of the child frames are also minimized. When the main frame is restored, all the children are similarly restored. This is accomplished within the anonymous WindowAdapter inner class. Note that you do need to keep a reference to the child frames, which the sample program does using a Vector.

import java.lang.reflect.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Test2
{
  private Vector children;
  public static void main(String[] args)
  {
    Test2 t = new Test2();
    t.init();
  };
  private void init()
  {
    children = new Vector();
    JButton button = new JButton("Pop up a child frame");
    JFrame frame = new JFrame("Main Frame");
    frame.getContentPane().add(button);
    button.addActionListener(
      new ActionListener()
      {
        public void actionPerformed(ActionEvent evt)
        {
          JFrame f = new JFrame("Child Frame");
          children.addElement(f);
          f.getContentPane().add(new JLabel("Child Frame"));
          f.pack();
          f.setVisible(true);
         }
       }
  );
  frame.addWindowListener(
    new WindowAdapter()
    {
      public void windowDeiconified(WindowEvent evt)
      {
        Enumeration e = children.elements();
        while (e.hasMoreElements())
        {
          JFrame f = (JFrame)e.nextElement();
          f.setState(Frame.NORMAL);
        }
      }
      public void windowIconified(WindowEvent evt)
      {
        Enumeration e = children.elements();
        while (e.hasMoreElements())
        {
          JFrame f = (JFrame)e.nextElement();
          f.setState(Frame.ICONIFIED);
        }
      }
    }
  );
  frame.pack();
  frame.setVisible(true);
  }
}
Random Walk Computing is the largest Java/CORBA consulting boutique in New York, focusing on solutions for the financial enterprise. Known for their leading-edge Java expertise, Random Walk consultants publish and speak about Java in some of the most respected forums in the world.