Alyona
Alyona

Reputation: 1792

How to bind label to first letter of StringProperty?

I have StringProperty that consists of two letters (example: 06) that are constantly changing. I have two labels, which I want to bind to each letter of StringProperty, like label1="0" and label2="6". Is there a way to bind label to specific letter of StringProperty?

My code:

@FXML
private Label hoursLabel1;

@FXML
private Label hoursLabel2;

private StringProperty hours;

@FXML
private void initialize() {
    hoursLabel1.textProperty().bind(hours);
}

Upvotes: 1

Views: 580

Answers (1)

James_D
James_D

Reputation: 209663

Use Bindings.createStringBinding(...):

@FXML
private void initialize() {
    hoursLabel1.textProperty().bind(Bindings.createStringBinding(() -> 
        hours.get().substring(0,1), hours));
    hoursLabel2.textProperty().bind(Bindings.createStringBinding(() -> 
        hours.get().substring(1,2), hours));
}

Upvotes: 4

Related Questions