How to append multicolor text in JavaFx textArea

3

This is actually my first JavaFx desktop application. Within my application I want to display every event as a log in textarea. I have different log types , error,warning etc. I want to append all these logs inside a textarea with different colors. I tried like this(this is just a sample),

 // Method call is like this
  logText("Enter Ip address First");


// The method 
public void logText(String log){
        log = ">> "+ log +"\n";
        Text t = new Text();
        t.setStyle("-fx-background-color: #DFF2BF;-fx-text-fill: #4F8A10;-fx-font-weight:bold;");
        t.setText(log);
        txtConsole.appendText(t.toString());
    } 

With above code I did not get any error but my output is like :

    Text[text=">> Enter Ip address First
", x=0.0, y=0.0, alignment=LEFT, origin=BASELINE, boundsType=LOGICAL, font=Font[name=System Regular, family=System, style=Regular, size=12.0], fontSmoothingType=GRAY, fill=0x000000ff]

How can I solve this ? I tried various methods mentioned here in stackoverflow (this is one of them).

*** Please note that this application is for corporate use so I need to be strict to the licenses.

Thanks in advance.

javafx
textarea
asked on Stack Overflow Mar 19, 2015 by Nepal12

1 Answer

8

You need to have replace t.toString() with t.getText() in txtConsole.appendText(t.toString())

You can't have colored text in TextArea. Try using TextFlow instead.

You have colored text which you can add to the TextFlow:

public class TextFlowSample extends Application {

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

    @Override
    public void start(Stage stage) {
        TextFlow flow = new TextFlow();
        String log = ">> Sample passed \n";
        Text t1 = new Text();
        t1.setStyle("-fx-fill: #4F8A10;-fx-font-weight:bold;");
        t1.setText(log);
        Text t2 = new Text();
        t2.setStyle("-fx-fill: RED;-fx-font-weight:normal;");
        t2.setText(log);
        flow.getChildren().addAll(t1, t2);
        stage.setScene(new Scene(new StackPane(flow), 300, 250));
        stage.show();
    }
}

If you have the flexibility to use external library, have a look at RichTextFX

answered on Stack Overflow Mar 19, 2015 by ItachiUchiha • edited May 3, 2018 by Neuron

User contributions licensed under CC BY-SA 3.0