如何在用户不活动后关闭JFrame?
到目前为止,我有,
Thread.sleep(10000);
如果有人可以给我代码来执行此操作,我将不胜感激?
我是Java的新手,希望了解有关系统安全性的更多信息
答案 0 :(得分:4)
这是Braj使用javax.swing.Timer
的想法的一个例子。
它简化了过程,因为您不需要监视事件之间的时间并确保在触发计时器时事件发生在事件调度线程中,从而进一步降低了复杂性。
另请注意,我已将AWTEvent.MOUSE_MOTION_EVENT_MASK
和AWTEvent.MOUSE_WHEEL_EVENT_MASK
个事件包括在内,以便进行更好的衡量;)
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class AutoClose {
public static void main(String[] args) {
new AutoClose();
}
private Timer timer;
private JLabel label;
private JFrame frame;
public AutoClose() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
label = new JLabel("Waiting...");
frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
private int count;
@Override
public void eventDispatched(AWTEvent event) {
Object source = event.getSource();
if (source instanceof Component) {
Component comp = (Component) source;
Window win = null;
if (comp instanceof Window) {
win = (Window) comp;
} else {
win = SwingUtilities.windowForComponent(comp);
}
if (win == frame) {
timer.restart();
label.setText("Interrupted..." + (++count));
}
}
}
}, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK);
timer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
// You could use a WindowListener to start this
timer.start();
}
});
}
}
答案 1 :(得分:3)
试试这个
要遵循的步骤:
以下是示例代码:
private long time;
...
long eventMask = AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK;
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent e) {
time = System.currentTimeMillis();
}
}, eventMask);
time = System.currentTimeMillis();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (System.currentTimeMillis() - time > 10000) {
widnow.dispose();
break;
}
}
}
}).start();