java awt run_java – 使用AWT关闭一个Frame(不是整个应用...

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) {

/* AFAIU starting the GUI on the EDT only applies to Swing.*/

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);

}

});

}

}

典型输出

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 . . .

更新1

此代码以编程方式关闭“Window 2”.您的版本的问题是“计时”,这是由稍后调用调用引起的(您认为这意味着什么?).它可以用两种相对简单的方法中的一种来固定.

> kludge.添加一个Swing Timer / ActionListener设置为在主运行后2秒关闭.对于该路线,请取出主要中所有注释代码行的“注释部分”.

>更好的解决方案.删除对EventQueue.invokeLater()的调用,该调用与AWT组件无关.

这是改变的代码:

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值