问题描述
右键单击TextField时,有撤消,重做,剪切,复制,粘贴,删除和全选选项。
When you right click on a TextField there are Undo, Redo, Cut, Copy, Paste, Delete, and Select All options.
我想添加一个将MenuItem从我的控制器类注册到该列表,但不知道如何。
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);
这两个都返回null:
Both of these return null:
charName.getContextMenu()
charName.contextMenuProperty().getValue()
推荐答案
您可以通过设置自己的(如下所示)来替换内置的TextField ContextMenu:
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);
}
}
添加到内置的ContextMenu有点过时,需要覆盖非公共API。
Adding to the in-built ContextMenu is a bit tricker and requires overriding non-public API.
您无法使用公共 textField.getContextMenu
属性获取内置的ContextMenu,因为它未被返回(方法只返回由应用程序代码设置的菜单,而不是内部JavaFX控件外观实现。
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).
请注意,以下代码几乎肯定会在Java 9中中断,因为它使用了弃用的 com.sun
API
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);
}
}
这篇关于JavaFX附加到TextField的右键菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!