0

I have a DatePicker and want to add a new MenuItem to ContextMenu of it.

DatePicker inputDate = new DatePicker();

try{

    MenuItem clearInput = new MenuItem("Clear");
    clearInput.setOnAction(e -> {
        inputDate.getEditor().clear();
        inputDate.setValue(null);
    });

    inputDate.getContextMenu() //returns null
            .getItems()
            .add(0, clearInput);

}catch(Exception e){
    e.printStackTrace();
}

At this code I get NullPointerException at .getItems(), which means inputDate.getContextMenu() is null.

Why getContextMenu() returns null?

And how to fix it?

Or how to add a new MenuItem to ContextMenu of DatePicker?

KunLun
  • 3,109
  • 3
  • 18
  • 65
  • wondering why you expect the picker to have a contextMenu (if you haven't set any)? If you mean the editor's default, ask the editor :) – kleopatra Mar 23 '21 at 11:59
  • @kleopatra, It has `ContextMenu`, because when I right click on input, the menu shows up (Undo, Redo, Copy, ...). Even `inputDate.getEditor().getContextMenu()` returns null. – KunLun Mar 23 '21 at 12:10
  • yeah, you are right: the default contextMenu (that what you are seeing on right click) is managed by the behaviour which is not related to the contextMenuProperty of the control. Probably hard to change (maybe going dirty somehow to get hold of it), you might replace it completely, though. – kleopatra Mar 23 '21 at 12:16
  • @kleopatra , I replaced the default `ContextMenu` with a new one and with my `MenuItem`. It works perfectly. Fortunately that I don't need default `MenuItem`s. Thank you for your time @kleopatra . – KunLun Mar 23 '21 at 12:32
  • glad you found a solution :) Closing this as duplicate (because the complete replace meets your requirement) – kleopatra Mar 23 '21 at 12:35

0 Answers0