Ok, I have a ListView object. I'm using this as a sort of console window for my server. It was really the only way I could think of to display colorized text in a box like that. Which this works wonderful so far. Now what I want to be able to do is color different text on one index or line.
Example:
listView[0] = "Hello " + "world";
Where "Hello" would be green and "world" would be blue. If this can be done usine javafx Text or any other way I would like to know how to go about it. I'm using Javafx Text as the primary culprit since you can customize so much with it.
I hope everyone can understand what I'm trying to do here, if not, let me know and I'll try to reword it a bit.
SOLUTION
Thanks to jewelsea I was able to figure out a solution. I went with a bit of a different approach with it instead of using a 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();
}
}
"Working Example"
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…