Der*_*ekE 4 java javafx colors
好的,我有一个ListView对象.我正在使用它作为我的服务器的一种控制台窗口.这是我能想到的唯一一种在这样的盒子中显示彩色文本的方法.到目前为止,这项工作很精彩.现在我想要做的是在一个索引或行上为不同的文本着色.
例:
listView[0] = "Hello " + "world";
Run Code Online (Sandbox Code Playgroud)
其中" Hello "为绿色," world "为蓝色.如果这可以用usine javafx文本或任何其他方式我想知道如何去做.我使用Javafx Text作为主要元凶,因为你可以用它自定义这么多.
我希望每个人都能理解我在这里要做的事情,如果没有,请告诉我,我会尝试重新改写一下.
解
感谢jewelsea,我能够找到解决方案.我采用了一种不同的方法,而不是使用cellfactory.
列表显示
ListView<FlowPane> consoleWindow = new ListView<>();
ArrayList<FlowPane> consoleBuffer = FXCollections.observableArrayList();
consoleWindow.setItems(consoleBuffer);
inputBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.ENTER) {
consoleBuffer.add(parseInput.parseInputToArray(inputBox.getText()));
}
consoleWindow.scrollTo(consoleBuffer.size());
}
});
Run Code Online (Sandbox Code Playgroud)
ConsoleInputParse:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
"工作实例"