To add ContextMenu to TextField in JavaFX
// Create the edit context menu items. MenuItem cut = new MenuItem("Cut"); MenuItem copy = new MenuItem("Copy"); MenuItem paste = new MenuItem("Paste"); // Create a context (i.e., pop up) menu that shows edit options. ContextMenu editMenu = new ContextMenu(cut, copy, paste); // Set the action event handlers. cut.setOnAction(e->{/* w w w. j a v a 2 s . c o m*/ String name = ((MenuItem) e.getTarget()).getText(); response.setText(name + " selected"); }); copy.setOnAction(e->{ String name = ((MenuItem) e.getTarget()).getText(); response.setText(name + " selected"); }); paste.setOnAction(e->{ String name = ((MenuItem) e.getTarget()).getText(); response.setText(name + " selected"); }); // Create a text field and set its column width to 20. TextField tf = new TextField(); tf.setPrefColumnCount(20); // Add the context menu to the text field. tf.setContextMenu(editMenu);
Full source
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class Main extends Application { //Create a label that will report the selection. private Label response = new Label("Menu Demo"); public static void main(String[] args) { launch(args);//from ww w. j a v a2s . co m } public void start(Stage myStage) { myStage.setTitle("Menus from java2s.com"); // Use a BorderPane for the root node. BorderPane rootNode = new BorderPane(); Scene myScene = new Scene(rootNode, 300, 300); myStage.setScene(myScene); // Create the edit context menu items. MenuItem cut = new MenuItem("Cut"); MenuItem copy = new MenuItem("Copy"); MenuItem paste = new MenuItem("Paste"); // Create a context (i.e., pop up) menu that shows edit options. ContextMenu editMenu = new ContextMenu(cut, copy, paste); // Set the action event handlers. cut.setOnAction(e->{ String name = ((MenuItem) e.getTarget()).getText(); response.setText(name + " selected"); }); copy.setOnAction(e->{ String name = ((MenuItem) e.getTarget()).getText(); response.setText(name + " selected"); }); paste.setOnAction(e->{ String name = ((MenuItem) e.getTarget()).getText(); response.setText(name + " selected"); }); // Create a text field and set its column width to 20. TextField tf = new TextField(); tf.setPrefColumnCount(20); // Add the context menu to the text field. tf.setContextMenu(editMenu); rootNode.setBottom(tf); rootNode.setCenter(response); myStage.show(); } }