繁体   English   中英

带有 cellfactory 的 javafx ComboBox 不显示所选项目

[英]javafx ComboBox with cellfactory does not display selected item

我有一个小的概念验证应用程序,其中包含 6 个Labels一个ComboBox和一个Button ,所有这些都使用 SceneBuilder 创建。

通过单击Button ,应用程序进行 Json api 调用以返回国家列表及其相关详细信息(apla2code、apla3code、名称等)。 我创建了一个CountryDetails对象,其中包含 3 个String元素。 我用它来返回一个CountryDetails数组,然后我将其加载到ObserbavleList数组中。 然后我将它应用到ComboBox并且每次在ComboBox选择一个项目时我将CountryDetails元素加载到 3 个标签中。 所有这些都可以正常工作(尽管可能有更好的方法来做到这一点)。

我遇到的问题是ComboBox没有显示所选项目,我不知道如何纠正这个问题。 下图显示了问题所在。

进行api调用的代码如下:

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetCountries {

    public CountryDetails[] getDetails() {

        String inputLine            = "";
        StringBuilder jsonString    = new StringBuilder();

        HttpURLConnection urlConnection;

        try {
            URL urlObject = new URL("https://restcountries.eu/rest/v2/all");

            urlConnection = (HttpURLConnection) urlObject.openConnection();
            urlConnection.setRequestMethod("GET");

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((inputLine = bufferedReader.readLine()) != null) {
                jsonString.append(inputLine);
            }
            urlConnection.getInputStream().close();

        } catch(IOException ioe) {
            System.out.println(ioe.getMessage());
        }

        Countries[] countries = new Gson().fromJson(jsonString.toString(), Countries[].class);

        CountryDetails[] countryDetails = new CountryDetails[countries.length];

        for(int i = 0; i < countries.length; i++){

            countryDetails[i] = new CountryDetails(
                    countries[i].getAlpha2Code(),
                    countries[i].getAlpha3Code(),
                    countries[i].getName()
            );
        }
        return countryDetails;
    }
} 

CountryDetails对象的代码如下:

public class CountryDetails {

    private String alpha2Code;
    private String alpha3Code;
    private String name;

    public CountryDetails(String strAlpha2Code, String strAlpha3Code, String strName) {
        this.alpha2Code = strAlpha2Code;
        this.alpha3Code = strAlpha3Code;
        this.name = strName;
    }

    public String getAlpha2Code() { return alpha2Code; }

    public void setAlpha2Code(String alpha2Code) { this.alpha2Code = alpha2Code; }

    public String getAlpha3Code() { return alpha3Code; }

    public void setAlpha3Code(String alpha3Code) { this.alpha3Code = alpha3Code; }

    public String getName() { return name; }

    public void setName(String name) {this.name = name; }
}

加载ObservableList的代码如下:

GetCountries countries = new GetCountries();

        CountryDetails[] countryDetails = countries.getDetails();

        for (CountryDetails countryDetail : countryDetails) {
            countriesObservableList.add(new CountryDetails(
                    countryDetail.getAlpha2Code(),
                    countryDetail.getAlpha3Code(),
                    countryDetail.getName())
            );
        }

加载ComboBox并显示Labels元素的代码如下:

    cbCountryList.setCellFactory(new Callback<ListView<CountryDetails>, ListCell<CountryDetails>>() {
            @Override public ListCell<CountryDetails> call(ListView<CountryDetails> p) {
                return new ListCell<CountryDetails>() {
                    @Override
                    protected void updateItem(CountryDetails item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty || (item == null) || (item.getName() == null)) {
                            setText(null);
                        } else {
                            setText(item.getName());
                        }
                    }
                };
            }
        });

    public void comboAction(ActionEvent event) {
        lblAlpha2Code.setText(cbCountryList.getValue().getAlpha2Code());
        lblAlpha3Code.setText(cbCountryList.getValue().getAlpha3Code());
        lblCountryName.setText(cbCountryList.getValue().getName());
    }

下面是该应用程序的图像:

在此处输入图片说明

我遇到的问题是 ComboBox 没有显示所选项目,我不知道如何纠正这个问题。

您需要为cbCountryList设置一个StringConverter

cbCountryList.setConverter(new StringConverter<CountryDetails>() {
    @Override
    public String toString(CountryDetails object) {
        return object.getName();
    }

    @Override
    public CountryDetails fromString(String string) {
        return null;
    }
});

所有这些都可以正常工作(尽管可能有更好的方法来做到这一点)。

您可以考虑更新以下内容,

  • 异步调用 HTTP 请求和加载项目
  • 每次触发按钮时,您都可以在调用时缓存fetched-country列表。 您可以为GetCountries创建一个Singleton对象。

修改了GetCountries

它缓存国家列表并将缓存的数据用于多个请求,

 public static class GetCountries {

    private static final String API_URL = "https://restcountries.eu/rest/v2/all";
    private static CountryDetails[] countryDetails;

    public static CountryDetails[] getDetails() {

        //uses cached countryDetails once it gets loaded
        if (countryDetails != null) {
            return countryDetails;
        }

        StringBuilder jsonString = new StringBuilder();
        HttpURLConnection urlConnection;
        try {
            URL urlObject = new URL(API_URL);

            urlConnection = (HttpURLConnection) urlObject.openConnection();
            urlConnection.setRequestMethod(HttpMethod.GET.name());

            String inputLine = "";

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((inputLine = bufferedReader.readLine()) != null) {
                jsonString.append(inputLine);
            }
            urlConnection.getInputStream().close();

        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }

        Countries[] countries = new Gson().fromJson(jsonString.toString(), Countries[].class);

        countryDetails = new CountryDetails[countries.length];
        for (int i = 0; i < countries.length; i++) {
            countryDetails[i] = new CountryDetails(
                    countries[i].getAlpha2Code(),
                    countries[i].getAlpha3Code(),
                    countries[i].getName()
            );
        }
        return countryDetails;
    }
}

使用Task异步获取您的国家/地区,

Task<CountryDetails[]> fetchCountryTask = new Task<CountryDetails[]>() {
    @Override
    protected CountryDetails[] call() throws Exception {
        return GetCountries.getDetails();
    }
};

fetchButton.setOnAction(event -> new Thread(fetchCountryTask).start());

fetchCountryTask.setOnRunning(event -> cbCountryList.setDisable(true));

fetchCountryTask.setOnSucceeded(e -> {
    cbCountryList.getItems().addAll(fetchCountryTask.getValue());
    cbCountryList.setDisable(false);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM