Search code examples
textareajavafxselectionhighlightingtextselection

How to know which text string is selected by user in JavaFX TextArea


I need to allow the user to highlight text (select a range with the mouse), then I want to give them the ability to apply some setting to that text form a drop down right click menu.

I know the latter part. But how do I get which text string is selected from a Text Area in JavafX?

Also, would I be able to apply different styles to different strings?


Solution

  • Use getSelectedText() to get the selected text.

    The answer to your second question is yes.

    The getSelectedText() method can be used like I have done here:

    import javafx.application.Application;
    import javafx.event.Event;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.TextArea;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class TextAreaDemo extends Application
    {
        @Override
        public void start(Stage stage)
        {
            final TextArea textArea = new TextArea("Text Sample");
            textArea.setPrefSize(200, 40);
    
            textArea.setOnContextMenuRequested(new EventHandler<Event>()
            {
                @Override
                public void handle(Event arg0)
                {
                    System.out.println("selected text:"
                        + textArea.getSelectedText());
                }
            });
    
            VBox vBox = new VBox();
            vBox.getChildren().addAll(textArea);
    
            stage.setScene(new Scene(vBox, 300, 250));
            stage.show();
        }
    
        public static void main(String[] args)
        {
            launch(args);
        }
    }
    

    Once you launch this application, it shows a TextArea with some text (Text Sample). I selected some part of the text and did a right click. It printed the selected text. Does this fit your requirement?