java textarea颜色,JavaFX Textarea中的多种颜色

How would I change the color of different text in a textarea in JavaFX? I've been doing some research, and I can only find solutions for Java Swing, not JavaFX.

To describe my situation, I'm trying to highlight different keywords in code, like a IDE. Basically, like this:

Nc5QB.png

In the above image, certain words are different colors.(.list is red, span is blue, etc.)

Does anyone know how to apply this effect to a JavaFX Textarea?

解决方案

RichTextFX lets you to assign different styles to different ranges of text. You will have to parse the CSS yourself, though. See the demo of highlighting Java keywords

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaFX,你可以使用RichTextFX库来实现TextArea部分文字的颜色和大小改变。 具体实现方法如下: 1. 引入RichTextFX库。 ``` <dependency> <groupId>org.fxmisc.richtext</groupId> <artifactId>richtextfx</artifactId> <version>0.10.4</version> </dependency> ``` 2. 创建一个样式类,用于设置需要改变的文字的颜色和大小。 ``` .highlight { -fx-fill: red; -fx-font-size: 20px; } ``` 这里将需要改变颜色和大小的文字的颜色设置为红色,字体大小设置为20px。 3. 创建一个RichTextArea,并将需要改变的文字用Span类包裹起来,并设置Span的样式。 ``` RichTextArea textArea = new RichTextArea(); textArea.setPlainText("这里是需要改变颜色和大小的文字"); int startIndex = textArea.getPlainText().indexOf("需要改变颜色和大小的文字"); int endIndex = startIndex + "需要改变颜色和大小的文字".length(); TextFlow textFlow = textArea.lookup("#text"); Span span = new Span("需要改变颜色和大小的文字"); span.getStyleClass().add("highlight"); textFlow.getChildren().set(textFlow.getChildren().indexOf(span), span); ``` 这里使用了RichTextArea的lookup()方法获取TextFlow,并使用Span类包裹需要改变颜色和大小的文字,并设置Span的样式。然后将Span替换TextFlow原有的文本。 注意,这种方法只适用于JavaFX的RichTextArea,并且需要引入RichTextFX库。如果需要将改变颜色和大小的文字提交到后端进行处理,需要将RichTextArea的内容提取出来,再提交到后端进行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值