Cardano Cardano - 1 month ago 8
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

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

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


Thats my button in FXML

<center>
<TextArea fx:id="textArea"/>
</center>


Thats
TextArea


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


And thats the method from controller.

Answer

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 {

    @Override
    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);

        scene.getStylesheets().add("centering-text-area.css");

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Comments