Cardano Cardano - 9 months ago 111
Java Question

Align content of a TextArea in JavaFX

I'm making a simple text editor for training purposes. I want to create a button which would center my text input from

just like in MS Word. I have my button in FXML, but I don't know what method should I use for my
object, I tried
but neither worked.

<Button onAction="#toTheCenter" text="center"/>

Thats my button in FXML

<TextArea fx:id="textArea"/>


private void toTheCenter(ActionEvent event){
String text = textArea.getText();

And thats the method from controller.

Answer Source

You need to set the -fx-text-alignment property on the text node of the text area.

The best way to do this dynamically is to define a custom CSS pseudoclass for the text area:

PseudoClass centered = PseudoClass.getPseudoClass("centered");

and then in your external CSS file you can do

.text-area:centered .text {
    -fx-text-alignment: center ;

Then you can call

textArea.pseudoClassStateChanged(centered, true);

to switch centering on, and

textArea.pseudoClassStateChanged(centered, false);

to switch it off.

Here is a SSCCE (put the CSS code above in centering-text-area.css):

import javafx.application.Application;
import javafx.css.PseudoClass;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class TextAreaWithCentering extends Application {

    public void start(Stage primaryStage) {

        TextArea textArea = new TextArea();

        PseudoClass centered = PseudoClass.getPseudoClass("centered");

        ToggleButton center = new ToggleButton("Center");
        center.selectedProperty().addListener((obs, wasCentered, isNowCentered) -> 
                textArea.pseudoClassStateChanged(centered, isNowCentered));

        BorderPane.setAlignment(center, Pos.CENTER);
        BorderPane.setMargin(center, new Insets(5));
        BorderPane root = new BorderPane(textArea, null, null, center, null);

        Scene scene = new Scene(root, 600, 600);



    public static void main(String[] args) {