如何在JavaFx textArea中附加多色文本

Nep*_*l12 3 textarea javafx

这实际上是我的第一个JavaFx桌面应用程序.在我的应用程序中,我想将每个事件显示为textarea中的日志.我有不同的日志类型,错误,警告等.我想将所有这些日志附加到具有不同颜色的textarea中.我试过这样的(这只是一个例子),

 // 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());
    } 
Run Code Online (Sandbox Code Playgroud)

使用上面的代码我没有得到任何错误,但我的输出如下:

    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]
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?我尝试了stackoverflow中提到的各种方法(这是其中之一).

***请注意,此应用程序仅供企业使用,因此我需要严格执照.

提前致谢.

Ita*_*iha 8

你需要t.toString()t.getText()in 替换txtConsole.appendText(t.toString())

TextArea中不能有彩色文本.请尝试使用TextFlow.

你有彩色文字,你可以添加到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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您可以灵活地使用外部库,请查看RichTextFX