[英]javafx Combobox<Integer> type mismatch
我的問題如下:
class xxx {
@FXML
private Combobox<Integer> cmb_year;
...
public void method ()
{
int year=2013;
cmb_year.getItems().add(year);
cmb_year.setValue(year) ---> argumenttype mismatch
}
}
它是我的代碼的片段,但顯示了我遇到的問題。
我嘗試過
總是導致參數類型不匹配。
是什么原因造成的?
如果要設置選擇的項目,則要使用ComboBox的SelectionModel:
cmb_year.getSelectionModel().select(cmb_year.getItems().indexOf(year));
您也可以嘗試setSelectedItem(year)
或selectLast()
。
這可能是ComboBox沒有正確或完全初始化的問題。 我從不“開箱即用”使用ComboBoxes。 我使用幾行代碼進行設置。
以下是我的一個對話框控制器類中的initialize()方法的代碼摘錄(此ComboBox顯示Institution對象的列表):
// this first line gets the data from my data source
// the ComboBox is referenced by the variable 'cbxInst'
ObservableList<Institution> ilist = Institution.getInstitutionList();
Callback<ListView<Institution>, ListCell<Institution>> cellfactory =
new Callback<ListView<Institution>, ListCell<Institution>>() {
@Override
public ListCell<Institution> call(ListView<Institution> p) {
return new InstitutionListCell();
}
};
cbxInst.setCellFactory(cellfactory);
cbxInst.setButtonCell(cellfactory.call(null));
cbxInst.setItems(ilist);
這里的關鍵點是:
我定義了一個單元工廠,以生成ListCell實例供ComboBox顯示。
我使用工廠創建一個ListCell實例來初始化Button Cell。
為了完整起見,這是用於創建Institution ListCell實例的私有成員類:
private final class InstitutionListCell extends ListCell<Institution> {
@Override
protected void updateItem(Institution item, boolean empty){
super.updateItem(item, empty);
if (item != null) {
this.setText(item.getName());
} else {
this.setText(Census.FORMAT_TEXT_NULL);
}
}
}
如果以類似的方式初始化ComboBox,則可能會解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.