import java.awt.*; import java.awt.event.*; public class Test11 extends Frame { public Test11(String title) { super(title); setSize(400, 400); setBackground(Color.red); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.out.println( getTitle() + " says Bye-Bye! " + new java.util.Date()); dispose(); } }); setLocationByPlatform(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { System.out.println("Run: Window 1"); (new Test11("Window 1")).setVisible(true); System.out.println("Run: Window 2"); (new Test11("Window 2")).setVisible(true); } }); } }
Typical output
Run: Window 1 Run: Window 2 Window 1 says Bye-Bye! Mon Nov 14 10:20:25 EST 2011 Window 2 says Bye-Bye! Mon Nov 14 10:20:35 EST 2011 Press any key to continue . . .
Update 1
This code programmatically closes "Window 2". The problem with your version was the "time" caused by the call to call later (what do you think it means?). It can be fixed in one of two relatively simple ways.
- Cold Add the Swing
Timer / ActionListener set to 2 seconds after the main runs. For this route, output the "comment part" of all lines of the comment code in the main one. - The best solution. Remove the call to
EventQueue.invokeLater() , which is not related to AWT components.
Here is the modified code:
import java.awt.*; import java.awt.event.*; // since the OP has not taken the time to explain 'why AWT', // I choose to make life easy by using a Swing class. import javax.swing.Timer; public class Test11 extends Frame { public static Frame window1; public static Frame window2; public Test11(String title) { super(title); setSize(400, 400); setBackground(Color.red); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.out.println( getTitle() + " says Bye-Bye! " + new java.util.Date()); dispose(); } }); setLocationByPlatform(true); } public static void main(String[] args) { // AFAIU starting the GUI on the EDT only applies to Swing. //EventQueue.invokeLater(new Runnable() { // public void run() { System.out.println("Run: Window 1"); window1 = new Test11("Window 1"); window1.setVisible(true); System.out.println("Run: Window 2"); window2 = new Test11("Window 2"); window2.setVisible(true); // } //}); //ActionListener closeWindow = new ActionListener(){ // public void actionPerformed(ActionEvent ae) { System.out.println( window2.getTitle() + " says Bye-Bye! " + new java.util.Date()); /* failed then try */ window2.dispose(); // } //}; //Timer timer = new Timer(2000,closeWindow); //timer.setRepeats(false); //timer.start(); } }
source share