From some time I try to change row color according to property value in FXCollections
(after editing cell: true -> green row, false -> red row). In one SO question there is information to use Observable
. I still don't know how to use it and now I try to understand @kleopatra's post. I added 3 items to choiceBox
and then after clicking a button I would like to change one of them. Every click adds a line to choiceBox
. Why? Do I need refresh this or something? I started to display all items every click and the number of items remains the same, even this one is changed. Can anyone explain me how to edit this in proper way?
Main.java:
public class Main extends Application {
public static int i = 0;
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
primaryStage.setTitle("Hello World");
ObservableList<Test> items = FXCollections.observableArrayList(e -> new Observable[]{e.nameProperty()});
Test test1 = new Test("test1");
Test test2 = new Test("test2");
Test test3 = new Test("test3");
Button button = controller.getButton();
button.setOnAction(e -> {
test1.setName("name changed" + ++i);
});
items.addAll(test1, test2, test3);
ChoiceBox choiceBox = controller.getChoiceBox();
choiceBox.setItems(items);
StringConverter<Test> converter = new StringConverter<Test>() {
@Override
public String toString(Test album) {
return album != null ? album.getName() : null;
}
@Override
public Test fromString(String string) {
return null;
}
};
choiceBox.setConverter(converter);
Scene scene = new Scene(root, 300, 275);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
sample.fxml:
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<ChoiceBox fx:id="choiceBox" GridPane.columnIndex="0" GridPane.rowIndex="0"></ChoiceBox>
<Button fx:id="button" GridPane.columnIndex="0" GridPane.rowIndex="1" text="CHANGE"></Button>
</GridPane>
Controller.java:
public class Controller {
@FXML
private ChoiceBox choiceBox;
@FXML
private Button button;
public ChoiceBox getChoiceBox() {
return choiceBox;
}
public void setChoiceBox(ChoiceBox choiceBox) {
this.choiceBox = choiceBox;
}
public Button getButton() {
return button;
}
public void setButton(Button button) {
this.button = button;
}
}
Test.java:
class Test {
StringProperty name;
public Test(String name) {
setName(name);
}
public StringProperty nameProperty() {
if (name == null) name = new SimpleStringProperty(this, "name");
return name;
}
public void setName(String name) {
nameProperty().set(name);
}
public String getName() {
return nameProperty().get();
}
}