datEmperor
datEmperor

Reputation: 33

JavaFX ListView color the text

I have this simple code:

public class ControllerList {
@FXML ListView listView;
@FXML Button btnSend;
@FXML ColorPicker colorPicker;
@FXML TextField textField;

  public void clickSend() {
      listView.getItems().add(textField.getText());
  }
}   

I need to color the text added to the ListView using the color picker. How can i do that?

Upvotes: 3

Views: 2228

Answers (1)

James_D
James_D

Reputation: 209684

Create a class to encapsulate the text and color:

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 ;
    }
}

and then use a ListView<ColoredText> with a cell factory:

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()));
    }

}   

Upvotes: 3

Related Questions