本文介绍了如何在JavaFx textArea中附加多色文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]

我该如何解决?我尝试了在stackoverflow中提到的各种方法(这是其中一种).

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.

先谢谢了.

推荐答案

您需要将t.toString()替换为txtConsole.appendText(t.toString())

您不能在TextArea中添加彩色文本.尝试改用 TextFlow

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

您有彩色文本,可以添加到TextFlow:

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

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

这篇关于如何在JavaFx textArea中附加多色文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 08:43