如何在Java应用程序中添加系统退出事件处理机制(转载)

如何在Java应用程序中添加系统退出事件处理机制(转载),第1张

具体演示代码如岁羡下:/**********************************************************************************************************************************************************/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) {}}})}/***************************************************** 这是程序的入口,仅为演示,方法中的代码无关紧察雀搏要***************************************************/

用JFrame写的java小应用是直接带有窗口的,在main()中加上setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)。

如果想写颤者则茄棚点击事件来实现关闭窗嫌差口,试试 System.exit(0)

给按钮添加 ActionPerform 事件 内容写System.exit(0);

package com.lx

import java.awt.Button

import java.awt.FlowLayout

import java.awt.Frame

import java.awt.event.ActionEvent

import java.awt.event.ActionListener

public class Test implements ActionListener {

Frame f = new Frame()

public static void main(String[] args) {

Test t = new Test()

t.init()

}

private void init() {

Button b = new Button("exit")

b.addActionListener(this)

f.add(b)

f.setLayout(new FlowLayout())

f.setSize(100,100)

f.setVisible(true)

}

public void actionPerformed(ActionEvent arg0) {

f.setVisible(false)

f.dispose()

System.exit(0)

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12343209.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存