首页 > 解决方案 > ActionListener 中的 TextField getText() 问题

问题描述

我在控制台中工作,我想将文本转换为带有颜色代码的 html 格式。如果我从文本字段发送文本,我无法替换字符,并且我的文本不会被转换。这是一个例子:

我的测试代码:

WebViewConsole webViewConsole = new WebViewConsole();
        webViewConsole.appendText("§1This is a §l§2Test §r§1, just §l§2because§r§1!\n");

        TextField textField = new TextField();
        textField.setText("§1This is a §l§2Test §r§1, just §l§2because§r§1!\n");
        System.out.println(textField.getText().replaceAll("§", ""));
        System.out.println(textField.getText().contains("§"));

        Button button = new Button("Send");
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                for (String htmlText : webViewConsole.getHtmlFormat(textField.getText())) {
                    System.out.println(htmlText);
                }
                String text = textField.getText();
                webViewConsole.appendText(textField.getText());
                System.out.println(text.replaceAll("§", ""));
                System.out.println(text.contains("§"));
            }
        });

        HBox hBox = new HBox(textField, button);

        VBox vBox = new VBox(webViewConsole.getConsole(), hBox);

        primaryStage.setScene(new Scene(vBox, 500, 300));
        primaryStage.show();

截图: 截图

输出(我发送了一次消息):

1This is a l2Test r1, just l2becauser1!
true
<span style="color:white;font-weight:normal"></span>
<span style="color:blue;font-weight:normal">This is a </span>
<span style="color:darkgreen;font-weight:bold">Test </span>
<span style="color:white;font-weight:normal"></span>
<span style="color:blue;font-weight:normal">, just </span>
<span style="color:darkgreen;font-weight:bold">because</span>
<span style="color:white;font-weight:normal"></span>
<span style="color:blue;font-weight:normal">!</span>
1This is a l2Test r1, just l2becauser1!
true

如果消息包含该 stange 字符(屏幕截图),则文本将成功转换。

对不起我的英语不好,谢谢你的帮助!

标签: javafxactionlistenertextfield

解决方案


推荐阅读