Mohamed Benmahdjoub
Mohamed Benmahdjoub

Reputation: 1280

JavaFX: modify button text in real time

I have a button with a ContextMenu which contains a MenuItem rename.
rename.setOnMouseClicked is supposed to give the possibility to change the text in the button : The user can actually delete a letter in the text or write it then press enter to validate what he was typing, somehow working as textField.

Is it possible to do this ? if so, how can i ? Thanks!

Upvotes: 3

Views: 16897

Answers (1)

J Atkin
J Atkin

Reputation: 3140

Yes

Here's how:

public class EditableButtonApp extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();

        root.setCenter(new EditableButton("Editable Button"));

        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    class EditableButton extends Button {
        TextField tf = new TextField();

        public EditableButton(String text) {
            setText(text);
            setOnMouseClicked(e -> {
                tf.setText(getText());
                setText("");
                setGraphic(tf);
            });

            tf.setOnAction(ae -> {
//              if (validateText(tf.getText())) {// this is where you would validate the text
                setText(tf.getText());
                setGraphic(null);
//            }
            });
        }
    }

    public static void main(String[] args) { launch(args); }
}

Upvotes: 4

Related Questions