1 Reply Latest reply: Dec 4, 2012 1:02 PM by James_D RSS

    "Paste" filtering

    edward17
      Is there such a thing as a paste event?

      I would like to filter the results of a paste action (keys or mouse) and respond differently if, say, the string is 4 characters versus 12.
        • 1. Re: "Paste" filtering
          James_D
          edward17 wrote:
          Is there such a thing as a paste event?
          Not that I'm aware of.
          I would like to filter the results of a paste action (keys or mouse) and respond differently if, say, the string is 4 characters versus 12.
          I'm assuming you're referring to pasting text into a TextInputControl (TextField or TextArea). You have a couple of options. One is to listen for changes on the text property of the control and react accordingly. That might be a little ugly, since if you want to "veto" the paste you'll need to change it back right after it was changed, and so on.

          The other way is to override the paste() method in the control itself. Something like
          import javafx.application.Application;
          import javafx.scene.Scene;
          import javafx.scene.control.Label;
          import javafx.scene.control.TextField;
          import javafx.scene.input.Clipboard;
          import javafx.scene.layout.VBox;
          import javafx.stage.Stage;
          
          public class PasteVetoExample extends Application {
          
            @Override
            public void start(Stage primaryStage) {
              final VBox root = new VBox();
              final Label label = new Label("");
              final TextField textField = new TextField() {
                @Override
                public void paste() {
                  String clipboard = Clipboard.getSystemClipboard().getString();
                  if (clipboard != null && clipboard.length() > 4) {
                    label.setText("Text too long");
                  } else {
                    label.setText("");
                    super.paste();
                  }
                }
              };
              root.getChildren().addAll(label, textField);
              primaryStage.setScene(new Scene(root));
              primaryStage.show();
            }
          
            public static void main(String[] args) {
              launch(args);
            }
          }
          Edited by: James_D on Dec 4, 2012 11:01 AM (Added check for null on clipboard's String content.)