好吧,我有一个ListView对象。我使用它作为我的服务器的一种控制台窗口。这是我能想到在这种盒子中显示彩色文本的唯一方法。这到目前为止效果很好。现在我想要做的是在一个索引或行上为不同的文本添加颜色。Javafx文本多字着色
例子:
listView[0] = "Hello " + "world";
其中 “你好” 将是绿色, “世界” 将是蓝色的。如果这可以通过使用javafx文本或任何其他方式,我想知道如何去做。我使用Javafx Text作为主要罪魁祸首,因为您可以自定义它。
我希望每个人都能理解我在这里要做的事情,如果没有,请告诉我,我会尽量对它进行一点说明。
SOLUTION
感谢jewelsea我能找出一个解决方案。我用了一些不同的方法来代替使用cellfactory。
的ListView
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());
}
});
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();
}
}
“工作实施例”
您是否有任何资源可以分享关于cellfactory如何工作,或者如何建立类似客户的东西。 javafx的那部分总是让我困惑。 – DerekE 2013-02-26 06:22:03
Tom Schindl [实施了某些东西](http://tomsondev.bestsolution.at/2013/02/20/from-styledtextviewer-to-a-styledtexteditor-with-javafx8/)使用ListView和Java 8 TextFlow ',但这可能是你想要的矫枉过正。我会看看我能否把一个基本的例子放在一起。 – jewelsea 2013-02-26 06:44:31
基于ListView + FlowPane +多个Text节点的组合,添加到[样本解决方案](https://gist.github.com/jewelsea/5036908)的链接。 – jewelsea 2013-02-26 08:39:31