JavaFX Append to right click menu for TextField

2019-07-14 12:15发布

问题:

When you right click on a TextField there are Undo, Redo, Cut, Copy, Paste, Delete, and Select All options.

I want to add a "Register" MenuItem to that list from my controller class, but do not know how.

Here is what I got so far:

This overwrites the existing menu items:

ContextMenu contextMenu = new ContextMenu();
MenuItem register = new MenuItem("Register");
contextMenu.getItems().add(register);
charName.setContextMenu(contextMenu);

Both of these return null:

charName.getContextMenu()
charName.contextMenuProperty().getValue()

回答1:

You can replace the in-built TextField ContextMenu by setting your own (as below):

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

public class GiveMeContext extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        ContextMenu contextMenu = new ContextMenu();
        MenuItem register = new MenuItem("Register");
        contextMenu.getItems().add(register);

        TextField textField = new TextField();
        textField.setContextMenu(contextMenu);

        stage.setScene(new Scene(textField));
        stage.show();
    }
    public static void main(String[] args) throws Exception {
        launch(args);
    }
}

Adding to the in-built ContextMenu is a bit tricker and requires overriding non-public API.

You cannot get the in-built ContextMenu using the public textField.getContextMenu property as it is not returned (that method only returns a menu that has been set by the application code, not the internal JavaFX control skin implementation).

Be aware that the following code will almost certainly break in Java 9 as it uses deprecated com.sun APIs which will likely no longer be available. For further details on this, refer to JEP 253: Prepare JavaFX UI Controls & CSS APIs for Modularization

import com.sun.javafx.scene.control.skin.TextFieldSkin;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

public class GiveMeContext extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        TextField textField = new TextField();
        TextFieldSkin customContextSkin = new TextFieldSkin(textField) {
            @Override
            public void populateContextMenu(ContextMenu contextMenu) {
                super.populateContextMenu(contextMenu);
                contextMenu.getItems().add(0, new SeparatorMenuItem());
                contextMenu.getItems().add(0, new MenuItem("Register"));
            }
        };
        textField.setSkin(customContextSkin);

        stage.setScene(new Scene(textField));
        stage.show();
    }
    public static void main(String[] args) throws Exception {
        launch(args);
    }
}