不可编辑的组合框的设置值

问题描述 投票:1回答:1

有人可以分享一些示例代码来设置不可编辑的组合框的值吗?它类似于this,但是当我尝试将其插入代码中时。它返回一个空值

代码

ObservableList<City> data = FXCollections.observableArrayList();
data = AddressGetWay.getCityByProvince("Batanes")
cmbCity.setItems(data); // set the items from the database

cmbCity.setConverter(new StringConverter<City>() {

        @Override
        public String toString(City object) {
                return object.getCityName();
        }

        @Override
        public City fromString(String string) {
               return cmbCity.getItems().stream().filter(ap
                      -> ap.getCityName().equals(string)).findFirst().orElse(null);
        }
 });

cmbCity.valueProperty().addListener(
    (ObservableValue<? extends City> observable, City oldValue, City newVal) -> {
       if (newVal != null) {
          //
        }
     }
);

// TODO: get the data stored in the database (Column City)
//  and set the value of the ComboBox.

Predicate<City> predicate = city -> city.getCityName() == "Itbayat"; // Let's assume that the data stored in the database is "Itbayat"
Optional<City> opt = data.stream().filter(predicate).findAny();
cmbCity.getSelectionModel().select(opt.orElse(null)); // the ComboBox value should be "Itbayat".

我正在使用Singleton类(如果我错了,请纠正我)从数据库中检索数据

public class AddressGetWay {

    static Connection con; //connect to the database
    static PreparedStatement pst = null;
    static ResultSet rs = null;

    public static ObservableList<City> getCityByProvince(String prov) {
        ObservableList<City> listData = FXCollections.observableArrayList();
        String sql = "SELECT pk_cit_id, cit_nm, zip_code FROM city_mun WHERE prov_code = (SELECT prov_code FROM provinces WHERE prov_nm = ?)";

        try {
            pst = con.prepareStatement(sql);
            pst.setString(1, prov);
            rs = pst.executeQuery();

            while (rs.next()) {
                listData.add(new City(
                        rs.getInt(1),
                        rs.getString(2),
                        rs.getInt(3)
                ));
            }
        } catch (SQLException ex) {
            Logger.getLogger(AddressGetWay.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                pst.close();
                rs.close();
            } catch (SQLException ex) {
                Logger.getLogger(AddressGetWay.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return listData;
    }
}

这应该是我想要的输出

desired output

但是我使用上面的代码得到了这个输出

my output

关于我的命名约定。如果有需要纠正的地方,我尝试做this,请随时查明。

combobox javafx-8
1个回答
1
投票

似乎您在此代码块上有问题,

ObservableList<City> data = AddressGetWay.getCityByProvince("Batanes");

//....

Predicate<City> predicate = city -> city.getCityName() == "Itbayat";
Optional<City> opt = data.stream().filter(predicate).findAny();
cmbCity.getSelectionModel().select(opt.orElse(null));

我怀疑某些loop-holes克服了null-value

  • 当您通过省份Batanes检索数据,即ObservableList<City> data = AddressGetWay.getCityByProvince("Batanes")时,可能没有检索任何数据。
  • 您的谓词正在比较cityName Itbayat,它可能与检索到的数据不匹配。
  • 请同时检查城市表的数据库值以比较这些数据

AddressGateWay

public class AddressGateWay {

    private static Connection connection;
    private static PreparedStatement statement = null;
    private static ResultSet result = null;

    static {
        connection = loadConnection();
    }

    public static ObservableList<City> getCityByProvince(String prov) {
        ObservableList<City> listData = FXCollections.observableArrayList();
        String sql = "SELECT pk_cit_id, cit_nm, zip_code FROM city_mun WHERE prov_code = (SELECT prov_code FROM provinces WHERE prov_nm = ?)";

        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, prov);
            result = statement.executeQuery();

            while (result.next()) {
                listData.add(new City(
                        result.getInt(1),
                        result.getString(2)
                ));
            }
        } catch (SQLException ex) {
            Logger.getLogger(AddressGateWay.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                statement.close();
                result.close();
            } catch (SQLException ex) {
                Logger.getLogger(AddressGateWay.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return listData;
    }

    // for editing
    public static ObservableList<Address> selectedItem(int item) {
            ObservableList<Address> listData = FXCollections.observableArrayList();
            String sql = "SELECT prov_nm, city_nm FROM emp_address WHERE pk_address_id = ?";

            try {
                statement = connection.prepareStatement(sql);
                statement.setString(1, item);
                result = statement.executeQuery();

                if (result.next()) {
                    listData.add(new Address(
                            result.getString(1),
                            result.getString(2)
                    ));
                }
            } catch (SQLException ex) {
                Logger.getLogger(AddressGateWay.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    statement.close();
                    result.close();
                } catch (SQLException ex) {
                    Logger.getLogger(AddressGateWay.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            return listData;
        }
}

城市

public class City {
    private int id;
    private String cityName;

    public City(int id, String cityName) {
        this.id = id;
        this.cityName = cityName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
}

控制器逻辑代码

ObservableList<City> cities = AddressGateWay.getCityByProvince(provinceComboBox.getValue()); // assume the value is "Batanes"
    cityComboBox.setItems(cities);

cityComboBox.setConverter(new StringConverter<City>() {
    @Override
    public String toString(City object) {
        return object.getCityName();
    }

    @Override
    public City fromString(String string) {
        return cityComboBox.getItems().stream().filter(ap
                -> ap.getCityName().equals(string)).findFirst().orElse(null);
    }
});
cityComboBox.valueProperty().addListener(
        (ObservableValue<? extends City> observable, City oldValue, City newVal) -> {
            if (newVal != null) {
                //
            }
        }
);

City city = cities
        .stream()
        .filter(c -> c.getCityName() == "Itbayat")
        .findAny()
        .orElse(null);

cityComboBox.getSelectionModel().select(city);



// summing up the below updates and your codes,
// I have set the value of cityComboBox by using . . .

Address ads = new Address();
ads = AddressGetWay.selectedItem(item); // the item to be edit

// assume the value from the database is "Itbayat"
Predicate<City> predicate = city -> city.getCityName() == ads.getCity().getCityName();

Optional<City> opt = cities.stream().filter(predicate).findAny();

cityComboBox.getSelectionModel().select(opt.orElse(null));

// Thank you, it finally work :)

一些基于更新代码的关键点

  • 基于不必要的代码重构代码
  • 实现基本的Java命名约定
  • 缺少连接初始化(需要根据您的数据库加载)
  • 内部代码(用于谓词和可选)

编辑

public class Province {
     private String provinceCode;
     private String provinceName;

     //Constructors
     //Getters and Setters
}

地址

public class Address {
     private City city;
     private Province province;

     //Constructors
     //Getters and Setters

}
© www.soinside.com 2019 - 2024. All rights reserved.