JAVAFX 8 ComboBox和ObservableList

时间:2016-03-02 10:15:48

标签: javafx combobox observablelist

我需要一个通过observablelist填充的组合框,其中包含从DB检索的特定数据。这是我的来源。

模型

public ObservableList<Bank> listBank = FXCollections.observableArrayList();

public static class Bank {
            private final StringProperty id;
            private final StringProperty name;

            private Bank(
                    String id, 
                    String name
            ) {
            this.id = new SimpleStringProperty(id);
            this.name = new SimpleStringProperty(name);        
            }

            public StringProperty idProperty() { return id; }
            public StringProperty nameProperty() { return name; }        
        }

查看

@FXML
private ComboBox comboBank<Bank>;

public final void getBankDataFields() {
        comboBank.setItems(model.listBank); 
    }

comboBank.setButtonCell(new ListCell<Bank>() {
                @Override
                protected void updateItem(Bank t, boolean bln) {
                    super.updateItem(t, bln);
                    if (t != null) {
                        setText(t.nameProperty().getValue().toUpperCase());
                    } else {
                        setText(null);
                    }
                }
            });

comboBank.setCellFactory(new Callback<ListView<Bank>, ListCell<Bank>>() {
                @Override 
                public ListCell<Bank> call(ListView<Bank> p) {
                    return new ListCell<Bank>() { 
                        @Override
                        protected void updateItem(Bank t, boolean bln) {
                            super.updateItem(t, bln);
                            if(t != null){
                                setText(t.nomeProperty().getValue().toUpperCase());
                            } else {
                                setText(null);
                            }    

                        }                       
                    };
                }
            });

comboBank.valueProperty().addListener((ObservableValue<? extends Bank> observable, Bank oldValue, Bank newValue) -> {
                setIdBank(newValue.idProperty().getValue());
            });

ComboBox填充了NAME字段,侦听器用于获取相对ID并将其传递给查询以在DB上存储数据。

好的,一切似乎都有效,但我有两个问题:

  1. 当用户需要修改此记录时,我需要从DB获取ID并在ComboBox中选择相对NAME。我怎么能这样做?

    comboBank.setValue(????);

  2. 有没有更好的方法来实现这一目标? ObservableMap可以替换ObservableList?

  3. 提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以通过更轻松的方式实现目标。您应该在ComboBox上使用StringConverter来显示Bank实例的名称。

comboBox.setConverter(new StringConverter<Bank>() {

    @Override
    public String toString(Bank object) {
       return object.nameProperty().get();
    }

    @Override
    public Bank fromString(String string) {
       // Somehow pass id and return bank instance
       // If not important, just return null
       return null;
    }
});

要获取所选值,即所选银行的实例,只需使用:

comboBox.getValue();

<强> MCVE

import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.util.StringConverter;

import java.util.stream.Collectors;

public class Main extends Application {

    @Override
    public void start(Stage stage) {

        ComboBox<Bank> comboBox = new ComboBox<>();
        ObservableList<Bank> items = FXCollections.observableArrayList(
                new Bank("1", "A"), new Bank("2", "B"),
                new Bank("3", "C"), new Bank("4", "D"));
        comboBox.setItems(items);
        StringConverter<Bank> converter = new StringConverter<Bank>() {
            @Override
            public String toString(Bank bank) {
                return bank.nameProperty().get();
            }

            @Override
            public Bank fromString(String id) {
                return items.stream()
                        .filter(item -> item.idProperty().get().equals(id))
                        .collect(Collectors.toList()).get(0);
            }
        };
        comboBox.setConverter(converter);
        // Print the name of the Bank that is selected
        comboBox.getSelectionModel().selectedItemProperty().addListener((o, ol, nw) -> {
            System.out.println(comboBox.getValue().nameProperty().get());
        });
        // Wait for 3 seconds and select the item with id = 2
        PauseTransition pauseTransition = new PauseTransition(Duration.seconds(3));
        pauseTransition.setOnFinished(event -> comboBox.getSelectionModel().select(converter.fromString("2")));
        pauseTransition.play();
        VBox root = new VBox(comboBox);
        root.setAlignment(Pos.CENTER);
        Scene scene = new Scene(root, 200, 200);
        stage.setScene(scene);
        stage.show();
    }
}