JavaFX添加到右键菜单的TextField

3
当您右键单击文本字段时,会出现撤消、重做、剪切、复制、粘贴、删除和全选等选项。
我想从我的控制器类将“注册”菜单项添加到该列表中,但不知道如何操作。
以下是我的进展情况:
这将覆盖现有的菜单项:
ContextMenu contextMenu = new ContextMenu();
MenuItem register = new MenuItem("Register");
contextMenu.getItems().add(register);
charName.setContextMenu(contextMenu);

这两个都返回 null:

charName.getContextMenu()
charName.contextMenuProperty().getValue()
1个回答

6
您可以通过设置自己的TextField ContextMenu(如下)来替换内置的TextField上下文菜单:

enter image description here

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);
    }
}

在内置的ContextMenu中添加内容稍微有些棘手,需要覆盖非公共API。

你无法使用公共的textField.getContextMenu属性获取内置的ContextMenu,因为它不会被返回(该方法只返回由应用程序代码设置的菜单,而不是内部JavaFX控件皮肤实现)。

customcontext

请注意,以下代码几乎肯定会在Java 9中出现问题,因为它使用了已弃用的com.sun API,这些API可能不再可用。有关此问题的更多详细信息,请参阅JEP 253:为模块化准备JavaFX UI控件和CSS API

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);
    }
}

将此转换为函数,以便我只需调用addRegister()或addMenuItem(),这将帮助我在迁移到Java 9时进行更新。太棒了,@jewelsea的回答。 - milesacul
使用 9++,默认上下文菜单的管理已经移至行为(Behavior)中.. 不幸的是,这不可访问。幸运的是,答案的第一部分仍然成立 :) - kleopatra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接