【问题标题】:How to Encode String to display color text( based on the prefixes within String)如何编码字符串以显示彩色文本(基于字符串中的前缀)
【发布时间】:2018-06-26 19:13:50
【问题描述】:

我是 Java 新手,正在努力完成以下任务。 我正在编写一个应用程序,它将用户的输入(取决于一个人的选择)编码为在 Quake III Arena 的命令行解释器中编译的代码,这使玩家能够根据以下字符前缀为 nick 的字母着色(例如“^0Black ^3黄色) ^0 黑色 ^1 白色 ^2 绿色 ^3 黄色 ^4 蓝色 ^5 青色(浅蓝色) ^6 品红色紫色 ^7 白色 That is how app looks in current stage

代码工作正常,但我想根据输入生成一个彩色文本,通过单击生成预览尼克的当前外观。

在几次尝试后我放弃了,我不知道如何处理这个主题。任何事情都将不胜感激。我希望我足够具体。提前谢谢你。

【问题讨论】:

  • 您的正则表达式很简单:^[\\^]\d{1}\w+。这意味着:以 ^ 开头,然后是 1 的数字,然后是任何文本:^0TEXT

标签: java string javafx text colors


【解决方案1】:

您可以使用regular expression 提取文本部分,然后构建一个包含不同颜色文本元素的文本流。

这是一个演示。正则表达式查找两个不同的命名组:一个可选的^,后跟一个(命名为“colIndex”)数字,然后是(命名为“text”)任何不等于^ 的非零字符序列。文本字段上的侦听器只是遍历匹配项并构建 Text 元素。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;

public class TextFieldRegexExample extends Application {

    @Override
    public void start(Stage primaryStage) {

        Color[] colors = new Color[] {Color.BLACK, Color.WHITE, Color.GREEN, Color.YELLOW, Color.BLUE, Color.CYAN, Color.PURPLE};

        TextField textField = new TextField();
        Pattern pattern = Pattern.compile("(\\^(?<colorIndex>\\d))?(?<text>[^(\\^\\d)]+)");

        TextFlow textFlow = new TextFlow();

        textField.textProperty().addListener((obs, oldValue, newValue) -> {
            Matcher matcher = pattern.matcher(newValue);

            textFlow.getChildren().clear();

            while(matcher.find()) {
                String color = matcher.group("colorIndex");
                String text = matcher.group("text");
                Text t = new Text(text+" ");
                if (color != null && color.matches("\\d+")) {
                    int colIndex = Integer.parseInt(color);
                    if (colIndex >= 0 && colIndex < colors.length) {
                        t.setFill(colors[colIndex]);
                    }
                }
                textFlow.getChildren().add(t);
            }
        });

        VBox root = new VBox(5, textField, textFlow);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多