gpt4 book ai didi

java - 由于不活动而自动关闭 JavaFX 应用程序

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:37:29 28 4
gpt4 key购买 nike

如果用户一段时间不活动,我想关闭我的 JavaFX 应用程序。我在 Swing 中有这段代码,我想在 JavaFX 中做同样的事情。如果在指定时间内没有发生任何事件,此类会将用户重定向到登录面板。

import javax.swing.Timer;

public class AutoClose {

private Timer timer;

public AutoClose(JFrame centralpanel) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {

Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {

@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 == centralpanel) {
timer.restart();
}
}
}
}, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK);

timer = new Timer(3600000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {

centralpanel.dispose();

//Redirect to the login panel.
Login login = new Login();
login.setVisible(true);
timer.stop();
JOptionPane.showMessageDialog(null,"Connection closed due to inactivity");
}
});
timer.start();
}
});
}
}

最佳答案

创建一个 PauseTransition 来触发延迟退出,并为所有重新启动转换的场景添加一个 InputEvent 的事件过滤器:

@Override
public void start(Stage primaryStage) throws IOException {
Button button = new Button("abcde");
StackPane root = new StackPane(button);
Scene scene = new Scene(root, 400, 400);

// create transition for logout
Duration delay = Duration.seconds(10);
PauseTransition transition = new PauseTransition(delay);
transition.setOnFinished(evt -> logout());

// restart transition on user interaction
scene.addEventFilter(InputEvent.ANY, evt -> transition.playFromStart());

primaryStage.setScene(scene);
primaryStage.show();

transition.play();
}

private void logout() {
// TODO: replace with logout code
Platform.exit();
}

注意:使用事件过滤器很重要,因为事件可以在到达事件处理程序之前被消耗掉。

关于java - 由于不活动而自动关闭 JavaFX 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47590919/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com