Apps
Apps

Reputation: 3389

Programmatically display a message next to text field in JavaFX

I have a TextField in my JavaFX application. I want to programmatically display a message on the right side of the text (like the validation message). I thought of using Popup and setting the Label with message in that Popup. But I'm not sure how I can position this to the right side of the text field. Below is the sample code for this. Can you please help me with this?

public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX Welcome");
        GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));

        Text scenetitle = new Text("Welcome");
        scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
        grid.add(scenetitle, 0, 0, 2, 1);

        Label userName = new Label("User Name:");
        grid.add(userName, 0, 1);

        TextField userTextField = new TextField();
        grid.add(userTextField, 1, 1);

        Label pw = new Label("Password:");
        grid.add(pw, 0, 2);

        PasswordField pwBox = new PasswordField();
        grid.add(pwBox, 1, 2);


        Label label=new Label();
        label.setText("This is an error message");

        final Text actiontarget = new Text();
        grid.add(actiontarget, 1, 6);


        final Popup popup = new Popup(); 

        popup.getContent().add(label);

        //Want to display this popup to the right of the userTextField.

        Scene scene = new Scene(grid, 300, 275);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

Upvotes: 0

Views: 1890

Answers (1)

James_D
James_D

Reputation: 209553

After showing the stage, do

    Bounds userTextFieldBounds = userTextField.getBoundsInLocal();
    Point2D popupLocation = userTextField.localToScreen(userTextFieldBounds.getMaxX(), userTextFieldBounds.getMinY());
    popup.show(userTextField, popupLocation.getX(), popupLocation.getY());

The localToScreen(...) method was introduced in Java 8; if you are in an earlier version you will need

    Bounds userTextFieldBounds = userTextField.getBoundsInLocal();
    Point2D popupLocation = userTextField.localToScene(userTextFieldBounds.getMaxX(), userTextFieldBounds.getMinY());
    popup.show(userTextField, 
        popupLocation.getX()+scene.getX()+primaryStage.getX(), 
        popupLocation.getY()+scene.getY()+primaryStage.getY());

Upvotes: 2

Related Questions