How to find out which text string the user has selected in JavaFX TextArea

I need to allow the user to select the text (select the range with the mouse), then I want to give them the opportunity to apply some settings to this text form in the drop-down menu of the right mouse button.

I know the last part. But how do I get which text string is selected from the text area in JavafX?

Also, can I apply different styles for different lines?

+4
source share
1 answer

Use getSelectedText()to get selected text.

The answer to the second question is yes.

getSelectedText() , :

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);
    }
}

TextArea (Text Sample). . . ?

+5

All Articles