同一窗口中的 Javafx 弹出窗口(如上下文菜单)

标签 java javafx

我有一个按钮,如果用户单击该按钮,应该会出现一个菜单。但它应该在同一个窗口中!

Button button = new Button("Advanced Search");
Pane popup = getPopupMenu();
button.setOnAction((event) -> {
    //how to show the popup ontop of the hall stage?
});

`

最佳答案

您可以使用JFoenix Popup为了实现您的需求,这个代码示例也许对您有帮助:

package javafxpopup;

import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXPopup;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 *
 * @author Menai Ala Eddine
 */
public class JavaFXPopup extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction((ActionEvent event) -> {
            buildContextMenu().show(btn);
        });

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    public JFXPopup buildContextMenu() {
        JFXPopup contextPop = new JFXPopup();      
        contextPop.setPopupContent(getItemsList());
        return contextPop;
    }

    private VBox getItemsList() {
        VBox boxItem = new VBox();
        Label addItem = new Label("Add File");
        Label editItem = new Label("Edit File");
        Label deleteItem = new Label("Delete File");
        boxItem.getChildren().addAll(addItem, editItem, deleteItem);
        return boxItem;

    }

}

结果是:

Show popop on button

如果您需要根据窗口更改弹出窗口的位置/偏移量,请使用这段代码:

 buildContextMenu().show(primaryStage, 0, 0, JFXPopup.PopupVPosition.TOP, JFXPopup.PopupHPosition.LEFT, 0, 0);

关于同一窗口中的 Javafx 弹出窗口(如上下文菜单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49536380/

相关文章:

java - Maven 资源过滤不替换属性

java - 反序列化复杂的 gson - Java

java - EJB 3.0 如何包装异常以便客户端可以处理它?

JavaFX 2.0 如何获得我的 GUI 生成器?哪个在旧的 JavaFX 中可用?

java - 如何使用intellij idea IDE将图像链接到html?

java - 在 Java 中使用公共(public)字段是否可以?

java - 寻找Java方法将多个按钮图像数据捆绑在一个文件中

javafx如何请求焦点在表格单元格上?

java - 将 EnumMap 包装在可观察的 SimpleMapProperty 中

JavaFX - 音乐开/关切换按钮(不起作用)