У меня есть небольшое приложение для проверки концепции, которое содержит 6 Labels
a ComboBox
и Button
, все они созданы с помощью SceneBuilder.
При нажатии Button
приложение создает Json вызов API для возврата списка стран и связанных с ними сведений (apla2code, apla3code, name et c). Я создал объект CountryDetails
, который содержит 3 String
элементов. Я использую это для возврата массива CountryDetails
, который затем загружаю в массив ObserbavleList
. Затем я применяю это к ComboBox
и загружаю элементы CountryDetails
в 3 метки каждый раз, когда элемент выбирается в ComboBox
. Все это прекрасно работает (хотя, вероятно, есть гораздо лучший способ сделать это).
Проблема, с которой я столкнулся, заключается в том, что 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());
}
Ниже изображение приложения:
![enter image description here](https://i.stack.imgur.com/QvtLp.png)