gpt4 book ai didi

javafx - JavaFX ContextMenu不会自动隐藏

转载 作者:行者123 更新时间:2023-12-04 17:18:47 25 4
gpt4 key购买 nike

我有一个JavaFX ContextMenu分配给滚动面板的鼠标右键单击。它会打开,但在滚动 Pane 外部单击时不会关闭。我可以在滚动 Pane 中添加另一个鼠标事件以将其隐藏,但这只能解决1个问题。主要问题是,当我单击滚动 Pane 的任何组件时,上下文菜单仍保持打开状态。

示例:通过单击鼠标右键打开弹出窗口,然后单击按钮。弹出菜单仍处于打开状态。

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Main extends Application {

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

@Override
public void start(Stage primaryStage) {

final ContextMenu contextMenu = new ContextMenu();

MenuItem item1 = new MenuItem("About");
MenuItem item2 = new MenuItem("Preferences");

contextMenu.getItems().addAll(item1, item2);


Rectangle rect = new Rectangle( 100,100,150,150);
Button button = new Button( "Button Text");

// create nodes
Group root = new Group();
root.getChildren().add( rect);
root.getChildren().add( button);

// create scrollpane
ScrollPane sp = new ScrollPane( root);
sp.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {

if (event.isSecondaryButtonDown()) {
contextMenu.show( sp, event.getScreenX(), event.getScreenY());
}
}
});



// create scene
Scene scene = new Scene(sp, 400, 400, Color.WHITE);

// add scene to primary stage
primaryStage.setScene( scene);
primaryStage.show();
}
}

文档说有一个setAutoHide方法,但是在我的情况下不起作用:

Specifies whether Popups should auto hide. If a popup loses focus and autoHide is true, then the popup will be hidden automatically. The only exception is when owner Node is specified using show(javafx.scene.Node, double, double). Focusing owner Node will not hide the PopupWindow.

@defaultValue false



非常感谢你!

最佳答案

与父级的子级元素进行交互将使该父级获得焦点。因此,单击代码中的按钮时,上下文菜单不会隐藏。

尝试以下两种方法:
1)手动管理上下文菜单的可见性,即在单击按钮时将其隐藏:

button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
contextMenu.hide();
}
});

2)使用setContextMenu()代替在鼠标按下事件时显示上下文菜单:
sp.setContextMenu(contextMenu);

关于javafx - JavaFX ContextMenu不会自动隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26816116/

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