即使GUI不存在,我也在后台运行应用程序。这意味着我使用系统托盘来关闭应用程序或再次启动UI。启动时用户必须打开GUI然后如果他决定关闭它仍然有选项通过sys tray打开它。
问题是 - 关闭应用程序窗口(GUI)后,JAVAFX应用程序线程关闭,即使我使用引用从我的系统托盘Object调用start()方法。它什么都不做,不是太惊讶。所以如何我能克服这个问题吗?我可以手动启动FX应用程序线程并续订我的ui 吗?
我的启动方法如下所示
@Override
public void start(Stage primaryStage) throws Exception {
fxc = new FXMLMainViewController();
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"....just fxml path"
)
);
loader.setController(fxc);
Parent root = (Parent) loader.load();
Scene scene = new Scene(root);
stage = primaryStage;
stage.getIcons().add(new javafx.scene.image.Image(Todo.class.getResourceAsStream(".....just image path")));
stage.setTitle("TODO");
stage.setScene(scene);
stage.show();
if (isTray) {//protection from creating useless tray objects
tray = new Tray(stage, this);
isTray = false;
}
datMod.updateTable(fxc.tableView, fxc.getTcmns());
}
我的托盘类:
public class Tray {
private Stage stage;
private Application application;
public Tray(Stage stage, Application application) {
this.stage = stage;
this.application = application;
hookTray();
}
private void hookTray() {
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
} else {
try {
Todo.icon = new TrayIcon(ImageIO.read(Todo.class.getResourceAsStream("....image path")), "TODO application",
createPopupMenu());
Todo.icon.addActionListener((ActionEvent e) -> {
Platform.runLater(() -> {
stage.setIconified(false);
});
//some popup test
});
SystemTray.getSystemTray().add(Todo.icon);
//Thread.sleep(3000);
Todo.icon.displayMessage("TODO", "Listener enabled",
TrayIcon.MessageType.INFO);
} catch (AWTException | IOException ex) {
ex.printStackTrace();
}
}
}
private PopupMenu createPopupMenu() throws HeadlessException {
PopupMenu menu = new PopupMenu();
MenuItem exit = new MenuItem("Exit");
MenuItem showWindow = new MenuItem("Show window");
showWindow.addActionListener((ActionEvent e) -> {
//restart ui thread /renew gui
});
exit.addActionListener((ActionEvent e) -> {
System.exit(0);
});
menu.add(showWindow);
menu.add(exit);
return menu;
}
}
小记 - 我不想让我的GUI不合理,我想让它停止/删除它/没有它的痕迹。这就是为什么我使用系统托盘。