Javafx文本多字着色

Javafx文本多字着色,java,colors,javafx,Java,Colors,Javafx,好的,我有一个ListView对象。我使用它作为我的服务器的一种控制台窗口。这真的是我能想到的在这样一个框中显示彩色文本的唯一方法。到目前为止,这一切都很好。现在我想做的是在一个索引或一行上给不同的文本上色 例如: listView[0] = "Hello " + "world"; 其中“你好”“是绿色的,“世界””是蓝色的。如果这可以通过javafx文本或任何其他方式完成,我想知道如何进行。我使用Javafx文本作为主要的罪魁祸首,因为你可以用它定制很多东西 我希望每个人都能理解我在这里要做

好的,我有一个ListView对象。我使用它作为我的服务器的一种控制台窗口。这真的是我能想到的在这样一个框中显示彩色文本的唯一方法。到目前为止,这一切都很好。现在我想做的是在一个索引或一行上给不同的文本上色

例如:

listView[0] = "Hello " + "world";
其中“你好”“是绿色的,“世界””是蓝色的。如果这可以通过javafx文本或任何其他方式完成,我想知道如何进行。我使用Javafx文本作为主要的罪魁祸首,因为你可以用它定制很多东西

我希望每个人都能理解我在这里要做什么,如果没有,请让我知道,我会尝试改写一下

解决方案

多亏了朱厄西,我才想出了一个解决办法。我使用了一种不同的方法,而不是使用手机工厂

列表视图

ListView控制台窗口=新建ListView();
ArrayList consoleBuffer=FXCollections.observableArrayList();
consoleWindow.setItems(consoleBuffer);
inputBox.setOnKeyPressed(新的EventHandler(){
@凌驾
公共无效句柄(KeyEvent KeyEvent){
if(keyEvent.getCode()==KeyCode.ENTER){
add(parseInput.parseInputToArray(inputBox.getText());
}
滚动到(consoleBuffer.size());
}
});
控制台输入解析

public class ConsoleInputParse {

    private String[] wordList = {};

    public ConsoleInputParse() {}

    public FlowPane parseInputToArray(String input) {
        wordList = input.trim().split("[ ]+");

        return colorize();
    }

    public FlowPane colorize() {

        ArrayList<Text> textChunks = new ArrayList<>();
        FlowPane bundle = new FlowPane();

        //Todo: use regex to check for valid words
        for (String word : wordList) {
            String spaced = word + " ";
            switch (word) {
                case "Hello": case "hello":
                    textChunks.add(customize(spaced, "purple"));
                    break;
                case "World": case "world":
                    textChunks.add(customize(spaced, "blue"));
                    break;
                case "Stack Overflow":
                    textChunks.add(customize(spaced, "orange", "Arial Bold", 15));
                default:
                    textChunks.add(customize(spaced, "black", "Arial",  13));
                    break;
            }
        }

        bundle.getChildren().addAll(textChunks);
        return bundle;
    }

    public Text customize(String word, String color) {
        return TextBuilder.create().text(word).fill(Paint.valueOf(color)).build();
    }

    public Text customize(String word, String color, String font) {
        return TextBuilder.create()
                .text(word)
                .fill(Paint.valueOf(color))
                .font(Font.font(font, 12)).build();
    }

    public Text customize(String word, String color, String font, int fontSize) {
        return TextBuilder.create()
                .text(word)
                .fill(Paint.valueOf(color))
                .font(Font.font(font, fontSize)).build();
    }

}
公共类控制台输入解析{
私有字符串[]字列表={};
公共控制台InputParse(){}
公共流程窗格ParseInputOarray(字符串输入){
wordList=input.trim().split(“[]+”);
返回colorize();
}
公共流窗格着色(){
ArrayList textChunks=新的ArrayList();
FlowPane bundle=新的FlowPane();
//Todo:使用正则表达式检查有效单词
for(字符串字:单词列表){
字符串间距=单词+“”;
开关(字){
案例“你好”:案例“你好”:
text chunks.add(自定义(间隔为“紫色”);
打破
案例“世界”:案例“世界”:
text chunks.add(自定义(间隔为“蓝色”);
打破
案例“堆栈溢出”:
添加(自定义(用空格隔开,“橙色”,“Arial粗体”,15));
违约:
添加(自定义(空格,“黑色”,“Arial”,13));
打破
}
}
bundle.getChildren().addAll(文本块);
返回包;
}
公共文本自定义(字符串字、字符串颜色){
返回TextBuilder.create().text(word).fill(Paint.valueOf(color)).build();
}
公共文本自定义(字符串字、字符串颜色、字符串字体){
返回TextBuilder.create()
.文本(word)
.填充(油漆.颜色值)
.font(font.font(font,12)).build();
}
公共文本自定义(字符串字、字符串颜色、字符串字体、int字体大小){
返回TextBuilder.create()
.文本(word)
.填充(油漆.颜色值)
.font(font.font(font,fontSize)).build();
}
}
“工作示例”

为您的创建自定义,并让它生成包含不同实例的单元格,每个实例具有不同的样式。我创建了一个示例来演示这种方法

样本输出:

在中,您可以使用设置文本样式,而不是在
流程窗格中组合不同的
文本
实例

示例代码

水果.css

FruitsDisplay.java

导入javafx.application.application;
导入javafx.collections.FXCollections;
导入javafx.scene.*;
导入javafx.scene.control.*;
导入javafx.scene.image.*;
导入javafx.scene.layout.*;
导入javafx.scene.text.text;
导入javafx.stage.stage;
导入java.util.*;
/**
*使用FlowPane在JavaFX中创建样式化文本的示例
*/
公共类水果显示扩展了应用程序{
私有静态最终字符串[]fruits={“apple”、“orange”、“pear”};
私有静态最终字符串[]fruitImageLocs={
"http://weknowyourdreamz.com/images/apple/apple-02.jpg",
"http://pic.1fotonin.com/data/wallpapers/165/WDF_2048871.png",
"http://vignette1.wikia.nocookie.net/pikmin/images/c/cc/Pear-01.jpg"
};
私有映射fruitImages=newhashmap();
公共静态void main(字符串[]args){
Application.launch(水果显示类);
}
@凌驾
public void start(Stage)引发异常{
舞台剧名(“水果故事”);
for(int i=0;inew-FroothFlowCell());
setPrefSize(440180);
场景=新场景(列表);
scene.getStylesheets().add(getResource(“fruits.css”);
舞台场景;
stage.show();
}
私有字符串getResource(字符串resourceName){
返回getClass().getResource(resourceName).toExternalForm();
}
私有类FlowCell扩展了ListCell{
静态最终字符串\u占位符=“%f”;
{
setContentDisplay(仅限ContentDisplay.GRAPHIC_);
}
@凌驾
受保护的void updateItem(字符串s,布尔值为空){
super.updateItem(s,空);
如果(s!)=null&&!“.equals&&&&!isEmpty()){
setGraphic(创建水果流);
}否则{
设置图形(空);
}
}
私有节点createFruitFlow(字符串s){
开关{
案例“苹果”:
public class ConsoleInputParse {

    private String[] wordList = {};

    public ConsoleInputParse() {}

    public FlowPane parseInputToArray(String input) {
        wordList = input.trim().split("[ ]+");

        return colorize();
    }

    public FlowPane colorize() {

        ArrayList<Text> textChunks = new ArrayList<>();
        FlowPane bundle = new FlowPane();

        //Todo: use regex to check for valid words
        for (String word : wordList) {
            String spaced = word + " ";
            switch (word) {
                case "Hello": case "hello":
                    textChunks.add(customize(spaced, "purple"));
                    break;
                case "World": case "world":
                    textChunks.add(customize(spaced, "blue"));
                    break;
                case "Stack Overflow":
                    textChunks.add(customize(spaced, "orange", "Arial Bold", 15));
                default:
                    textChunks.add(customize(spaced, "black", "Arial",  13));
                    break;
            }
        }

        bundle.getChildren().addAll(textChunks);
        return bundle;
    }

    public Text customize(String word, String color) {
        return TextBuilder.create().text(word).fill(Paint.valueOf(color)).build();
    }

    public Text customize(String word, String color, String font) {
        return TextBuilder.create()
                .text(word)
                .fill(Paint.valueOf(color))
                .font(Font.font(font, 12)).build();
    }

    public Text customize(String word, String color, String font, int fontSize) {
        return TextBuilder.create()
                .text(word)
                .fill(Paint.valueOf(color))
                .font(Font.font(font, fontSize)).build();
    }

}
/** 
 * fruits.css - place in same source directory as FruitsDisplay.java and 
 * ensure the build system copies the file over to the output path
 */
.root {
  -fx-font-size: 20px;
  -fx-font-family: "Comic Sans MS";
}

.list-cell {
  -fx-background-color: azure;
}

.fruit {
  -fx-font-weight: bold;
  -fx-font-style: italic;
}

.apple {
  -fx-fill: forestgreen;
}

.orange {
  -fx-fill: orange;
}

.pear {
  -fx-fill: gold;
}
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.util.*;

/**
 * Sample of using a FlowPane to create styled text in JavaFX
 */
public class FruitsDisplay extends Application {
    private static final String[] fruits = {"apple", "orange", "pear"};
    private static final String[] fruitImageLocs = {
            "http://weknowyourdreamz.com/images/apple/apple-02.jpg",
            "http://pic.1fotonin.com/data/wallpapers/165/WDF_2048871.png",
            "http://vignette1.wikia.nocookie.net/pikmin/images/c/cc/Pear-01.jpg"
    };
    private Map<String, Image> fruitImages = new HashMap<>();

    public static void main(String[] args) {
        Application.launch(FruitsDisplay.class);
    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setTitle("Fruit Tales");

        for (int i = 0; i < fruits.length; i++) {
            Image image = new Image(fruitImageLocs[i], 0, 30, true, true);
            fruitImages.put(fruits[i], image);
        }

        ListView<String> list = new ListView<>(FXCollections.observableArrayList(fruits));
        list.setCellFactory(listView -> new FruitFlowCell());
        list.setPrefSize(440, 180);

        Scene scene = new Scene(list);
        scene.getStylesheets().add(getResource("fruits.css"));
        stage.setScene(scene);
        stage.show();
    }

    private String getResource(String resourceName) {
        return getClass().getResource(resourceName).toExternalForm();
    }

    private class FruitFlowCell extends ListCell<String> {
        static final String FRUIT_PLACEHOLDER = "%f";

        {
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
        }

        @Override
        protected void updateItem(String s, boolean empty) {
            super.updateItem(s, empty);
            if (s != null && !"".equals(s) && !isEmpty()) {
                setGraphic(createFruitFlow(s));
            } else {
                setGraphic(null);
            }
        }

        private Node createFruitFlow(String s) {
            switch (s) {
                case "apple":
                    return createTextFlow("Eat an ", FRUIT_PLACEHOLDER, s, " a day.");
                case "orange":
                    return createTextFlow("An ", FRUIT_PLACEHOLDER, s, " has many vitamins.");
                case "pear":
                    return createTextFlow("A ", FRUIT_PLACEHOLDER, s, " has a funny shape.");
                default:
                    return null;
            }
        }

        private Node createTextFlow(String... msg) {
            FlowPane flow = new FlowPane();
            boolean isFruit = false;

            for (String s : msg) {
                if (FRUIT_PLACEHOLDER.equals(s)) {
                    isFruit = true;
                    continue;
                }

                Text text = new Text(s);
                if (isFruit) {
                    flow.getChildren().addAll(
                            new ImageView(fruitImages.get(s)),
                            createSpacer(5)
                    );
                    text.getStyleClass().addAll(
                            "fruit",
                            s
                    );
                    isFruit = false;
                } else {
                    text.getStyleClass().add("plain");
                }

                flow.getChildren().add(text);
            }

            return flow;
        }

        private Node createSpacer(int width) {
            HBox spacer = new HBox();
            spacer.setMinWidth(HBox.USE_PREF_SIZE);
            spacer.setPrefWidth(width);
            spacer.setMaxWidth(HBox.USE_PREF_SIZE);

            return spacer;
        }
    }
}