gpt4 book ai didi

java - 通知 Pane 未显示在场景中

转载 作者:行者123 更新时间:2023-11-30 06:46:14 25 4
gpt4 key购买 nike

我想在某些用户操作后显示通知 Pane 。我的应用程序有多个场景,NotificationPane 应该显示在当前 Activity 的场景中。

整个事情都与通知一起工作,当我需要它时它就会弹出。但我不知道如何使其适用于NotificationPane。

到目前为止我所做的步骤:

  • 我尝试将NotificationPane直接放入我的场景并调用show() - 它有效。
  • 现在的想法是通过调用获取当前 Pane stage.getScene().getRoot(),将其包装到NotificationPane,然后调用show() - 它不起作用,我不知道为什么。
  • ((BorderPane) pane).setCenter(new Label("TEST")); 这行代码用文本标签替换按钮,因此 stage.getScene().getRoot() 返回正确的对象

我编写了一个简单的程序来测试该行为。一键调用NotificationPane。有什么建议么?

这是我的测试程序:

package application;

import org.controlsfx.control.NotificationPane;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

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

@Override
public void start(Stage primaryStage) {
Button notificationPaneButton = new Button("NotificationPane");
notificationPaneButton.setOnAction(e -> showNotificationPane(primaryStage, "Notification text"));

VBox vbox = new VBox(5);
vbox.setAlignment(Pos.CENTER);
vbox.getChildren().addAll(notificationPaneButton);

BorderPane borderPane = new BorderPane();
borderPane.setCenter(vbox);

primaryStage.setTitle("Notifications test");
primaryStage.setScene(new Scene(borderPane, 300, 200));
primaryStage.show();
}

public void showNotificationPane(Stage stage, String message) {
Parent pane = stage.getScene().getRoot();
// ((BorderPane) pane).setCenter(new Label("TEST"));
NotificationPane notificationPane = new NotificationPane(pane);
notificationPane.setText(message);
if (notificationPane.showingProperty().get()) {
notificationPane.hide();
System.err.println("hide");
} else {
notificationPane.show();
System.err.println("show");
}

}
}

最佳答案

好的,我现在看到问题了。包装当前 Pane 还不够,我还必须将NotificationPane 添加到场景中。正确的?

无论如何,我当前的解决方案如下:

  • 获取当前场景
  • 获取当前 Pane
  • 包裹 Pane
  • 用新场景替换当前场景

为了避免多次换行 NotificationPane,我检查当前 Pane 是否已经是 NotificationPane,然后调用 show()

public void showNotificationPane(Stage stage) {
Scene scene = stage.getScene();
Parent pane = scene.getRoot();
if (!(pane instanceof NotificationPane)){
NotificationPane notificationPane = new NotificationPane(pane);
scene = new Scene(notificationPane, scene.getWidth(), scene.getHeight());
stage.setScene(scene);
notificationPane.show();
} else {
((NotificationPane)pane).show();
}
}

关于java - 通知 Pane 未显示在场景中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43651057/

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