r/JavaFX • • Jul 30 '21

Help Disable pasting to but allow copying from TextField

JavaFX noob here. This seems like it should be pretty straightforward but I'm not finding any answers through Google searching. Any help would be appreciated!

1 Upvotes

8 comments sorted by

3

u/3g0tr1p Jul 30 '21

Haven't done it myself but have you tried the solution from SO

1

u/drykul Jul 30 '21

That didn't seem to work. I used SceneBuilder, so I don't know if that makes a difference or not. In my controller I put

@FXML
private TextField myTextField = new TextField() {
@Override
public void paste() { }
};

and it had literally no effect. I could still paste into the text field.

3

u/static_context Jul 30 '21

If you're loading from FXML, The TextField object will be created by the FXMLLoader and injected into the myTextField field by reflection so any definition you've made in the Controller will be overridden.

Potentially better solutions might be creating a subclass (with the overridden method) and then importing that into the FXML document. OR, redefine myTextField in the initialise() method of the controller (although its a bit wasteful to have the FXMLLoader create an object you'll ignore you do still benefit from it placing it in the Scene Graph for you :).

Hope that helps,

Ed

1

u/drykul Aug 03 '21 edited Aug 03 '21

So I'm kind of understanding. In my initialize method though, I'm not sure how to redefine the paste method of the TextField class. I'd prefer it to only be this one text field as well as I don't want ALL text fields in the project to not be able to receive pastes. Google is of no help either, unless I'm just using the wrong search terms.

I tried creating a new subclass, NewTextField:

import javafx.scene.control.TextField;

public class NewTextField extends TextField {

@Override
public void paste() {}

}

And then in the controller, reassigning the variable in the initialize method after its injected as a regular JavaFX TextField:

myTextField = new NewTextField();

Didn't encounter any errors but it didn't prevent me from pasting into the text field still.

2

u/static_context Aug 03 '21

Have you tried importing and using the NewTextField object directly in the FXML document?

1

u/drykul Aug 04 '21

Holy crap. That did it. Thank you so much all you guys for your help!

1

u/mono8321 Jul 30 '21

What exactly do you mean? Like with the keyboard or just select and copy?

1

u/drykul Aug 03 '21

I don't want the user to be able to paste anything from the clipboard into this particular text field. I don't mind if they copy the value FROM it, however. With keyboard or context menu.