import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.Tab; import javafx.stage.Stage; public class ContextMenuTest extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { // for a button it is OK to set the context menu then nullify it Button b1 = new Button("B1"); b1.setContextMenu(createContextMenu("B1")); b1.setContextMenu(null); // but for a tab it throws an exception Tab t1 = new Tab("T1"); t1.setContextMenu(createContextMenu("T1")); t1.setContextMenu(null); stage.setScene(new Scene(b1)); stage.show(); } private static ContextMenu createContextMenu(String prefix) { final ContextMenu contextMenu = new ContextMenu(); MenuItem item1 = new MenuItem(prefix + ": About"); item1.setOnAction(new EventHandler() { public void handle(ActionEvent e) { System.out.println("About"); } }); MenuItem item2 = new MenuItem(prefix + ": Preferences"); item2.setOnAction(new EventHandler() { public void handle(ActionEvent e) { System.out.println("Preferences"); } }); contextMenu.getItems().addAll(item1, item2); return contextMenu; } }