我想在listView的行上使用上下文菜单项。在listView的MOUSE_CLICKED事件的事件处理程序中,getSelectionModel()。getSelectedItem()返回所选项,即好。但是,当我处理contextMenuItem的onAction事件时,它返回null。但是,图形化地选择了该项目。 有没有办法在第一次事件处理后“保留”选择?
以下是代码的相关部分:
ListView<Text> nameList = new ListView<>();
final ContextMenu cCm = new ContextMenu();
MenuItem cItem = new MenuItem("someText");
cCm.getItems().add(cItem);
...
nameList.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
if (e.getButton() == MouseButton.SECONDARY) {
//its OK here:
System.out.println(nameList.getSelectionModel().getSelectedItem().getText());
cCm.show(nameList, e.getScreenX(), e.getScreenY());
}
}
});
cItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
final Stage dialog = new Stage();
dialog.initModality(Modality.WINDOW_MODAL);
//nullPointerException on the following:
Text t = new Text(nameList.getSelectionModel().getSelectedItem().getText());
//showing dialog, etc.
答案 0 :(得分:3)
我几乎创建了你所做的完全复制品,我的实现工作:
private void initRandomCardListView() {
populateRandomList();
final ContextMenu randomListContextMenu = new ContextMenu();
MenuItem replaceCardMenuItem = new MenuItem("Replace");
replaceCardMenuItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
replaceRandomCard();
}
});
randomListContextMenu.getItems().add(replaceCardMenuItem);
randomCardList.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getButton().equals(MouseButton.SECONDARY)) {
randomListContextMenu.show(randomCardList, event.getScreenX(), event.getScreenY());
}
}
});
}
private void replaceRandomCard() {
System.out.println("jobs done");
System.out.println("card selected: " + randomCardList.selectionModelProperty().get().getSelectedItem().toString());
System.out.println("card index: " + randomCardList.getSelectionModel().getSelectedIndex());
System.out.println("card index: " + randomCardList.getSelectionModel().getSelectedItem().toString());
}
我没有任何空指针异常。总的来说,您的实施看起列表视图中的项目很可能出现问题。