Java Swing How to - Activate and deactivate frame








Question

We would like to know how to activate and deactivate frame.

Answer

import java.awt.Frame;
/*w w  w.  j a  v  a2  s  .  c  o m*/
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
  public static void main(String[] args) throws InterruptedException {
    JFrame frame = new JFrame();
    frame.add(new JLabel("Minimize demo"));
    frame.pack();

    // Show the frame
    frame.setVisible(true);

    // Sleep for 5 seconds, then minimize
    Thread.sleep(5000);
    frame.setState(Frame.ICONIFIED);

    // Sleep for 5 seconds, then restore
    Thread.sleep(5000);
    frame.setState(Frame.NORMAL);

    // Sleep for 5 seconds, then kill window
    Thread.sleep(5000);
    frame.setVisible(false);
    frame.dispose();

    // Terminate test
    System.exit(0);
  }
}