JavaFx HTMLEditor上的Intercept粘贴事件

Fer*_*uss 4 java javafx

您好,我想知道如何在JavaFX HTMLEditor中拦截粘贴事件

Rol*_*and 5

你不能 HTMLEditor在内部使用WebPage。基本上,在粘贴事件期间,它会通过以下方式发送“粘贴”命令

private boolean executeCommand(String command, String value) {
    return webPage.executeCommand(command, value);
}
Run Code Online (Sandbox Code Playgroud)

然后一个

twkExecuteCommand(getPage(), command, value);
Run Code Online (Sandbox Code Playgroud)

但是,您可以截取隐式调用粘贴事件的所有内容,例如单击按钮或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);
    }
}
Run Code Online (Sandbox Code Playgroud)

至于仅将纯文本粘贴到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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个变通方法,而且很丑陋,因为除非用户愿意,否则您永远不要修改剪贴板内容,但是它可以工作。另一方面,粘贴操作之后,剪贴板内容可以恢复为原始状态。

编辑:

您可以通过以下方式访问上下文菜单,例如禁用它:

WebView webView = (WebView) htmlEditor.lookup(".web-view");
webView.setContextMenuEnabled(false);
Run Code Online (Sandbox Code Playgroud)