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?

12/4/2013 6:52:30 PM

Accepted Answer

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
    public void start(Stage stage)
        final TextArea textArea = new TextArea("Text Sample");
        textArea.setPrefSize(200, 40);

        textArea.setOnContextMenuRequested(new EventHandler<Event>()
            public void handle(Event arg0)
                System.out.println("selected text:"
                    + textArea.getSelectedText());

        VBox vBox = new VBox();

        stage.setScene(new Scene(vBox, 300, 250));;

    public static void main(String[] 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?

12/4/2013 7:58:39 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow