我有这个简单的代码:
public class ControllerList {
@FXML ListView listView;
@FXML Button btnSend;
@FXML ColorPicker colorPicker;
@FXML TextField textField;
public void clickSend() {
listView.getItems().add(textField.getText());
}
}
我需要使用颜色选择器为添加到ListView的文本着色。 我怎么能这样做?
答案 0 :(得分:2)
创建一个类来封装文本和颜色:
public class ColoredText {
private final String text ;
private final Color color ;
public ColoredText(String text, Color color) {
this.text = text ;
this.color = color ;
}
public String getText() {
return text ;
}
public Color getColor() {
return color ;
}
}
然后使用ListView<ColoredText>
与单元格工厂:
public class ControllerList {
@FXML ListView<ColoredText> listView;
@FXML Button btnSend;
@FXML ColorPicker colorPicker;
@FXML TextField textField;
public void initialize() {
listView.setCellFactory(lv -> new ListCell<ColoredText>() {
@Override
protected void updateItem(ColoredText item, boolean empty) {
super.updateItem(item, empty);
if (item == null) {
setText(null);
setTextFill(null);
} else {
setText(item.getText());
setTextFill(item.getColor());
}
}
});
}
public void clickSend() {
listView.getItems().add(new ColoredText(textField.getText(), colorPicker.getValue()));
}
}