Javafx 列表视图上下文菜单 [英] Javafx ListView ContextMenu
问题描述
我已经查看了一些关于此的先前问题,但它们似乎仅起作用,即在列表视图中的任何位置单击都会触发事件,我正在寻找一种仅触发事件并打开上下文的解决方案单击列表视图中的属性时的菜单.
I've had a look at some previous questions on this but they only seem to work whereby a click anywhere in the listview will trigger the event, I am looking for a solution where the event would only be triggered and open a context menu when a property in the listview is clicked.
推荐答案
这实际上是重复的,但我找不到上一个问题.
This is actually a duplicate, but I can't find the previous question.
您应该使用单元工厂并在单元上设置上下文菜单.然后,您可以确保仅在非空单元格上设置上下文菜单.(这也让您有机会拥有特定于项目的上下文菜单.)
You should use a cell factory and set the context menu on the cells. You can then make sure you only set the context menu on non-empty cells. (This also gives you the opportunity to have item-specific context menus.)
这是一个简单的例子:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class ListViewContextMenuExample extends Application {
@Override
public void start(Stage primaryStage) {
ListView<String> listView = new ListView<>();
listView.getItems().addAll("One", "Two", "Three");
listView.setCellFactory(lv -> {
ListCell<String> cell = new ListCell<>();
ContextMenu contextMenu = new ContextMenu();
MenuItem editItem = new MenuItem();
editItem.textProperty().bind(Bindings.format("Edit "%s"", cell.itemProperty()));
editItem.setOnAction(event -> {
String item = cell.getItem();
// code to edit item...
});
MenuItem deleteItem = new MenuItem();
deleteItem.textProperty().bind(Bindings.format("Delete "%s"", cell.itemProperty()));
deleteItem.setOnAction(event -> listView.getItems().remove(cell.getItem()));
contextMenu.getItems().addAll(editItem, deleteItem);
cell.textProperty().bind(cell.itemProperty());
cell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
cell.setContextMenu(null);
} else {
cell.setContextMenu(contextMenu);
}
});
return cell ;
});
BorderPane root = new BorderPane(listView);
primaryStage.setScene(new Scene(root, 250, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
这篇关于Javafx 列表视图上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!