JavaFX 在没有外部库的情况下创建弹出窗口

标签 java javafx

如何从 javafx.scene.control.DatePicker 中的 DatePicker 类中创建弹出框,如下所示:

enter image description here

弹出框在显示时应位于所有其他组件之上,如此处所示(弹出框位于 TextField 上方):

enter image description here

最佳答案

找到了一个非常简单的解决方案,这里是一个代码片段,以防人们遇到同样的问题

package main;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Main extends Application {

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

    @Override
    public void start(Stage primaryStage) {
        BorderPane rootPane = new BorderPane();
        MenuButton openButton = new MenuButton("Open Context Menu");
        BorderPane contentPane = new BorderPane();
        CustomMenuItem item = new CustomMenuItem(contentPane);
        openButton.setStyle("-fx-selection-bar: transparent;"); //this is optional. it makes the blue background that appears when something is focused transparent
        contentPane.setPrefSize(300, 300);
        Label text = new Label("The ContextMenu will only close when you click the\nbutton below OR click outside of the ContextMenu.\nHow neat is that?");
        text.setStyle(" -fx-text-fill: -fx-text-base-color;"); //needs to bet set if you want the selection-bar to be transparent. if not set the text will become invisible
        contentPane.setTop(text);
        Button closeButton = new Button("Close this popover");
        closeButton.setOnAction(x -> {
            openButton.hide();
        });
        contentPane.setBottom(closeButton);
        item.setHideOnClick(false); // this will stop the ContextMenu from being hidden when clicking inside of it.
        openButton.getItems().add(item);
        rootPane.setCenter(openButton);
        Scene scene = new Scene(rootPane, 550, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

我只是在 CustomMenuItem 中放置了一个包含所有内容的 Pane 并将该 CustomMenuItem 添加到我的 MenuButton.

关于JavaFX 在没有外部库的情况下创建弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48622453/

相关文章:

java - 获取简单 RESTful Web 服务应用程序的错误页面

java - 从两个字符串数组返回公共(public)元素的最有效方法

java - 从 PDF 中提取文本位置

java - java.lang.module.ResolutionException:

java - 通知取代了 Android 中的旧版本

java - Spring MVC,如何经常轮询服务器的最佳实践

JavaFX 应用程序启动时间性能

java - 从第一个 Controller 传递值后,第二个 Controller 中不会显示值

java - 为什么在尝试将数据放入我的 JavaFX 散点图中时出现 IndexOutOfBoundsException?

java - 在 Swing JFrame 上添加 WebView 控件