如果用户在一段时间内处于非活动状态,我想关闭我的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();
}
});
}
}
答案 0 :(得分:4)
创建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();
}
注意:使用事件过滤器非常重要,因为事件可以在到达事件处理程序 之前消耗。
答案 1 :(得分:1)
我已完成此代码,现在它可以正常使用。
public class AutoClose {
private Timeline timer;
public AutoClose(VBox mainPanel) {
timer = new Timeline(new KeyFrame(Duration.seconds(3600), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent evt) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Inactivity");
alert.setHeaderText("Connection closed due to inactivity");
alert.show();
try {
Stage mainWindowStage = Login.getPrimaryStage();
Parent root = FXMLLoader.load(getClass().getResource("/view/Login.fxml"));
Scene scene = new Scene(root);
mainWindowStage.setScene(scene);
mainWindowStage.show();
timer.stop();
} catch (IOException ex) {
}
}
}));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();
mainPanel.addEventFilter(MouseEvent.ANY, new EventHandler<Event>() {
@Override
public void handle(Event event) {
timer.playFromStart();
}
});
}
}