具体
演示代码如岁羡下:/**********************************************************************************************************************************************************/package untitled14import java.util.*import java.io.*/*** This application is used to demo how to hook the event of an application*/public class Untitled1 {public Untitled1() {doShutDownWork()}/**************************************************************************** This is the right work that will do before the system shutdown* 这里为了演示,为
应用程序的退出增加了一个事件处理,* 当应用程序退出时候,败祥将程序退出的日期写入 d:\t.log文件**************************************************************************/private void doShutDownWork() {Runtime.getRuntime().addShutdownHook(new Thread() {public void run() {try {FileWriter fw = new FileWriter("d:\\t.log")System.out.println("I'm going to end")fw.write("the application ended! " + (new Date()).toString())fw.close()}catch (IOException ex) {}}})}/***************************************************** 这是程序的入口,仅为演示,方法中的
代码无关紧察雀搏要***************************************************/如果是要实现单击按钮退出,建议删掉这行态腊代码绝樱:
if(e.getActionCommand().equals("Eixt"))
或者,将实现接口的两个类变为public的内部类,同时稍微修改下,如下
import java.awt.*
import java.awt.event.*
public class lesson1 {
private Frame f
private Button b
public lesson1() {
f = new Frame("event")
b = new Button("Exit"帆宏滑)
}
public void launchFrame() {
b.addMouseListener(new ButtonHandler())
f.addWindowListener(new ClosingHander())
f.add(b, BorderLayout.CENTER)
f.setSize(400, 300)
f.setVisible(true)
f.setVisible(true)
f.setSize(400, 300)
}
public static void main(String args[]) {
lesson1 aa = new lesson1()
aa.launchFrame()
}
class ButtonHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e)
{
if (e.getSource() == b) {
System.exit(0)
}
}
}
class ClosingHander extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0)
}
}
}
评论列表(0条)