NotificationPane不会出现在Scene中

时间:2017-04-27 07:18:09

标签: java controlsfx

我想在某些用户操作后显示NotificationPane。我的应用程序有多个场景,NotificationPane应该出现在当前活动的场景中。

整个事情与Notification一起使用,它在我需要时弹出。 但我无法弄清楚如何使这项工作用于NotificationPane。

到目前为止我做的步骤:

  • 我尝试将NotificationPane直接放到我的场景中并调用 show() - 它有效。
  • 现在想法是通过调用来获取当前窗格 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");
        }

    }
}

1 个答案:

答案 0 :(得分:1)

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

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

  • 获取当前场景
  • 获取当前窗格
  • wrap pane
  • 用新的场景替换当前场景

为避免多次包裹NotificationPane,我会检查当前窗格是否已为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();
    }
}
相关问题