gpt4 book ai didi

java - 使用 javafx 发送通知而不使用 stage

转载 作者:行者123 更新时间:2023-12-02 00:54:08 25 4
gpt4 key购买 nike

您可以像这样使用 JavaFx 发送桌面通知(需要 jdk 8u20 或更高版本):

package sample;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import org.controlsfx.control.Notifications;

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception{
// Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Button notifyButton = new Button("Notify");
notifyButton.setOnAction(e -> {
Notifications.create().title("Test").text("Test Notification!").showInformation();
});
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(notifyButton, 100, 50));
primaryStage.show();
}


public static void main(String[] args) {
launch(args);
}
}

但是这样你就必须创建一个主窗口(舞台),有可能避免这种情况吗?我正在寻找一种发送通知的方法,例如在 bash 中使用 zenity:大多数代码都是非 GUI 的,但使用一些 gui 元素以非常基本的方式通知用户或与用户交互。

最佳答案

看起来 ControlsFX 通知需要现有阶段。您可以创建一个隐藏的实用程序阶段。尝试这样的事情。

package sample;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.controlsfx.control.Notifications;

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception{
}


public static void main(String[] args) {
new JFXPanel();
notifier("Good!", "It's working now!");
}

private static void notifier(String pTitle, String pMessage) {
Platform.runLater(() -> {
Stage owner = new Stage(StageStyle.TRANSPARENT);
StackPane root = new StackPane();
root.setStyle("-fx-background-color: TRANSPARENT");
Scene scene = new Scene(root, 1, 1);
scene.setFill(Color.TRANSPARENT);
owner.setScene(scene);
owner.setWidth(1);
owner.setHeight(1);
owner.toBack();
owner.show();
Notifications.create().title(pTitle).text(pMessage).showInformation();
}
);
}
}

new JFXPanel() 初始化 JavaFX 线程,而无需扩展 Application。您必须在调用 Platform.runLater() 之前调用此函数,否则您将收到线程异常。不过,您只需为整个应用程序调用一次即可。老实说,创建​​自己的通知阶段并直接显示可能会更好。创建一个像上面一样的舞台并放置您自己的内容。您也许可以重用 ControlsFX 源中的一些样式。

关于java - 使用 javafx 发送通知而不使用 stage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26875301/

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