JavaFX的ListView控件的ContextMenu [英] Javafx ListView ContextMenu
问题描述
我看了一下这方面的一些previous的问题,但他们只似乎工作,从而在ListView中点击任意位置将触发事件,我要寻找一个解决方案,该事件只会被触发,打开上下文菜单被点击列表视图物业时。
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.
推荐答案
这其实是一个重复的,但我找不到previous问题。
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.)
下面是一个简单的例子:
Here's a simple example:
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的ListView控件的ContextMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!