你好,我想知道如何在JavaFX HTMLEditor中拦截粘贴事件。
你不能。HTMLEditor在内部使用网页。基本上,在粘贴事件期间,它会通过发送"粘贴"命令
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);
}
}
这是一种变通方法,而且很难看,因为除非用户愿意,否则永远不应该修改剪贴板内容,但它是有效的。另一方面,可以在粘贴操作之后将剪贴板内容恢复到其原始状态。
编辑:
以下是如何访问上下文菜单,例如禁用它:
WebView webView = (WebView) htmlEditor.lookup(".web-view");
webView.setContextMenuEnabled(false);
不要尝试这一行,因为它总是返回NULL:
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"); });