你看一下图片,我只能右键单击并在单击橙色区域时获得上下文菜单。当我单击整个对象(如进度条等)时,我希望能够右键单击并获得上下文菜单。所有这些橙色项目都使用 ListView 显示,我使用 Hbox 来组织它们,因此复选框和进度栏可以位于某行上。我尝试过这个答案Javafx ListView ContextMenu但这并没有真正帮助。
这是我的代码
// Declare list that will hold the item
ObservableList<HBox> itemList = FXCollections.observableArrayList();
// Declare List View that will contain all the items
ListView itemlistView = new ListView<>();
// Get the items within the week
VBitem.displayByWeek();
// Add the items to the item list
for (int i = 0; i < VBitem.weekList.size(); i++) {
itemList.add(VBitem.weekList.get(i).display());
}
// Add the items to the list view
itemlistView.setitems(itemList);
// Style the list
itemlistView.getStylesheets().add(getClass().getResource("Main.css").toExternalForm());
// Add the list view to the scroll pane
fx_content_scroll.setContent(itemlistView);
itemlistView.setCellFactory(ly -> {
ListCell<HBox> cell = new ListCell<>();
ContextMenu contextMenu = new ContextMenu();
// Menu items
Menuitem editMenu = new Menuitem("Edit");
Menuitem deleteMenu = new Menuitem("Delete");
//System.out.println("Cell " + cell.getitem().item.info());
editMenu.textProperty().bind(Bindings.format("Edit \"%s\"",cell.itemProperty()));
//edititem.textProperty().bind(Bindings.format("Edit \"%s\"", cell.itemProperty()));
//editMenu.textProperty().bind(cell.itemProperty().asString());
editMenu.setOnAction(event -> {
System.out.println("HI "+cell.itemProperty());
//System.out.println("Just edited "+cell.getitem().item.info());
System.out.println("Editing");
});
// Add menu items to ContextMenu
contextMenu.getitems().addAll(editMenu, deleteMenu);
cell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
cell.setContextMenu(null);
} else {
cell.setContextMenu(contextMenu);
}
});
return cell;
});
最佳答案
根据我的理解,您希望在包含复选框和进度栏的 Pane 中的任何位置显示上下文菜单。向控件添加 ContextMenu 非常简单;您可以使用 Control.setContextMenu(...);
方法,但是,HBox 是一个 Pane ,而不是一个控件。
要将 ContextMenu 添加到 HBox,您可以使用 Node.setOnContextMenuRequested(...)
请求 ContextMenu 时接收事件的方法。在此期间,您可以在事件位置显示上下文菜单,从而达到所需的效果。
HBox box = new HBox();
box.getChildren().addAll(...);
MenuItem editMenu = new MenuItem("Edit");
editMenu.setOnAction(e -> {
// Do something
});
MenuItem deleteMenu = new MenuItem("Delete");
deleteMenu.setOnAction(e -> {
// Do something
});
ContextMenu menu = new ContextMenu(editMenu, deleteMenu);
box.setOnContextMenuRequested(e -> {
menu.show(box.getScene().getWindow(), e.getScreenX(), e.getScreenY());
});
这将在用于组织复选框和进度条的 HBox 内的任意位置打开一个上下文菜单。这可以轻松调整以适合您所需的区域。
关于java - 如何围绕整个对象设置上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48654408/