javaFX 关于stage的隐藏和显示问题
@tjumyk 你好,想跟你请教个问题:为什么我调用stage.hide()之后,再调用stage.show()的时候stage却无法显示出来呢?一下是我的代码。
package com.jhcomn.zsszn.client.view;
import java.awt.PopupMenu;
import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javafx.application.Application; import javafx.application.Platform; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.WindowEvent; import javax.imageio.ImageIO; public class ClientTray extends Application { private TrayIcon trayIcon; /** * @param args */ public static void main(String[] args) { launch(args); } @Override public void start(final Stage stage) throws Exception { enableTray(stage); Scene scene = new Scene(new Group(), 300, 200); stage.setScene(scene); stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent arg0) { stage.hide(); } }); } private void enableTray(final Stage stage) { PopupMenu popupMenu = new PopupMenu(); java.awt.MenuItem openItem = new java.awt.MenuItem("enable debug"); java.awt.MenuItem quitItem = new java.awt.MenuItem("exit"); ActionListener acl = new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { java.awt.MenuItem item = (java.awt.MenuItem) e.getSource(); if (item.getLabel().equals("exit")) { SystemTray.getSystemTray().remove(trayIcon); Platform.exit(); return; } if (item.getLabel().equals("enable debug")) { Platform.runLater(new Runnable() { @Override public void run() { stage.show(); } }); } } }; openItem.addActionListener(acl); quitItem.addActionListener(acl); popupMenu.add(openItem); popupMenu.add(quitItem); try { SystemTray tray = SystemTray.getSystemTray(); BufferedImage image = ImageIO.read(ClientTray.class .getResourceAsStream("trayicon.png")); trayIcon = new TrayIcon(image, "zsszn", popupMenu); trayIcon.setToolTip("zsszn"); tray.add(trayIcon); } catch (Exception e) { e.printStackTrace(); } } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢你的耐心解答,我明白了。
有以下几点需要清楚:
1. stage.hide() 与 stage.close() 等价, 详见http://docs.oracle.com/javafx/2/api/javafx/stage/Stage.html#close()
2. 如果要阻止Fx窗口在按下关闭按钮后退出,的确需要setOnCloseRequest,可是在handler函数中需要调用event.consume()来阻止事件进一步传递,这样才能真正阻止Window Close事件的默认处理。详见http://docs.oracle.com/javafx/2/api/javafx/stage/Window.html#onCloseRequestProperty
3. 默认情况下,Fx运行时会在最后一个stage close(或hide)后自动关闭,即自动调用Application.stop(),除非通过Platform.setImplicitExit(false)取消这个默认行为。这样,即使所有Fx窗口关闭(或隐藏),Fx运行时还在正常运行,可以再次显示原来的窗口或打开新的窗口。详见http://docs.oracle.com/javafx/2/api/javafx/application/Platform.html#setImplicitExit(boolean)