截获JavaFx HTMLEditor上的粘贴事件
您好,我想知道如何在JavaFX HTMLEditor中截取粘贴事件,您不能。HTMLEditor在内部使用网页。基本上在粘贴事件期间,它通过发送“粘贴”命令截获JavaFx HTMLEditor上的粘贴事件,java,javafx,Java,Javafx,您好,我想知道如何在JavaFX HTMLEditor中截取粘贴事件,您不能。HTMLEditor在内部使用网页。基本上在粘贴事件期间,它通过发送“粘贴”命令 private boolean executeCommand(String command, String value) { return webPage.executeCommand(command, value); } 然后是 twkExecuteCommand(getPage(), command, value); 但是
private boolean executeCommand(String command, String value) {
return webPage.executeCommand(command, value);
}
然后是
twkExecuteCommand(getPage(), command, value);
但是,您可以拦截隐式调用粘贴事件的所有内容,如按钮单击或CTRL+V组合键,具体取决于您希望对事件执行的操作
例如:
public class HTMLEditorSample extends Application {
@Override
public void start(Stage stage) {
final HTMLEditor htmlEditor = new HTMLEditor();
Scene scene = new Scene(htmlEditor, 800, 600);
stage.setScene(scene);
stage.show();
Button button = (Button) htmlEditor.lookup(".html-editor-paste");
button.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
System.out.println("paste pressed");
// e.consume();
});
htmlEditor.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
if( e.isControlDown() && e.getCode() == KeyCode.V) {
System.out.println( "CTRL+V pressed");
// e.consume();
}
});
}
public static void main(String[] args) {
launch(args);
}
}
对于仅将纯文本粘贴到html编辑器的用户,您可以这样做:
public class HTMLEditorSample extends Application {
@Override
public void start(Stage stage) {
final HTMLEditor htmlEditor = new HTMLEditor();
Scene scene = new Scene(htmlEditor, 800, 600);
stage.setScene(scene);
stage.show();
Button button = (Button) htmlEditor.lookup(".html-editor-paste");
button.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
modifyClipboard();
});
htmlEditor.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
if( e.isControlDown() && e.getCode() == KeyCode.V) {
modifyClipboard();
}
});
}
private void modifyClipboard() {
Clipboard clipboard = Clipboard.getSystemClipboard();
String plainText = clipboard.getString();
ClipboardContent content = new ClipboardContent();
content.putString(plainText);
clipboard.setContent(content);
}
public static void main(String[] args) {
launch(args);
}
}
这是一个解决办法,而且很难看,因为除非用户愿意,否则您永远不应该修改剪贴板内容,但它是有效的。另一方面,可以在粘贴操作后将剪贴板内容恢复到其原始状态
编辑:
下面是如何访问contextmenu,e。G要禁用它,请执行以下操作:
WebView webView = (WebView) htmlEditor.lookup(".web-view");
webView.setContextMenuEnabled(false);
不要尝试此行,因为它总是返回空值:
Button button = (Button) htmlEditor.lookup(".html-editor-paste");
从HTMLEditor获取粘贴按钮的唯一方法是@taha的解决方案:
htmlEditor.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> { if (e.getTarget().toString().contains("html-editor-paste")) { System.out.println("paste pressed"); });
这对于工具栏上的粘贴按钮和Ctrl+V操作非常有效,但是当我们从上下文菜单弹出窗口调用粘贴操作时,不会调用方法
modifyClipboard()
。是否存在从上下文菜单粘贴项中获取操作的方法?我添加了关于如何获取WebView的代码,以便您使用e。G禁用上下文菜单或添加自定义事件处理程序以添加您自己的上下文菜单。感谢我使用了webview和modifyClipbord()的方法setOnContextMenuRequested()
,效果非常好!这是有帮助的,我为鼠标点击监听器更改了它:htmlEditor.addEventFilter(MouseEvent.mouse_按下,e->{if(e.getTarget().toString().contains(“html编辑器粘贴”){System.out.println(“粘贴按下”);//e.consumere();});