You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX如何实现点击按钮在同一窗口弹出类似上下文菜单的Popup

How to Show a Custom Popup on Top of the Entire Stage in JavaFX

Hey David, I’ve got you covered! To make your custom pane popup display on top of your entire stage when the button is clicked, you’ll want to use JavaFX’s built-in Popup class—it’s designed exactly for this kind of top-level overlay scenario. Here’s how to adjust your code:

Step-by-Step Solution

  • Retrieve the parent Stage from your button: Since your button is part of the scene hierarchy, you can easily get the stage it’s attached to.
  • Wrap your custom pane in a Popup: This container handles overlay behavior and ensures your pane stays on top of the main stage.
  • Set the popup’s position (optional but flexible): You can position it relative to the button, center it on the stage, or place it anywhere else that fits your UI needs.

Updated Code

Button button = new Button("Advanced Search");
Pane popup = getPopupMenu();

button.setOnAction((event) -> {
    // Get the stage associated with the button
    Stage stage = (Stage) button.getScene().getWindow();
    
    // Create a Popup container and add your custom pane to it
    Popup popupContainer = new Popup();
    popupContainer.getContent().add(popup);
    
    // Example 1: Show the popup just below the button
    double buttonScreenX = button.localToScreen(0, 0).getX();
    double buttonScreenY = button.localToScreen(0, 0).getY() + button.getHeight();
    popupContainer.show(stage, buttonScreenX, buttonScreenY);
    
    // Example 2: Center the popup on the entire stage (uncomment to use)
    // double centerX = stage.getX() + stage.getWidth() / 2 - popup.getWidth() / 2;
    // double centerY = stage.getY() + stage.getHeight() / 2 - popup.getHeight() / 2;
    // popupContainer.show(stage, centerX, centerY);
});

Key Details

  • The Popup class ensures your pane acts as a top-level overlay, so it won’t be restricted to a smaller parent container.
  • Using show(stage, x, y) links the popup to your main stage—if the stage moves, the popup will stay in your specified relative position (you can add logic to reposition it dynamically if needed).
  • Double-check that your getPopupMenu() method returns a properly sized pane, otherwise the popup might appear empty or incorrectly scaled!

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:34:25