2016-11-17 46 views
0

我如何可以填補與ChoiceBox例如我的自定義課程中的StringProperty與自定義屬性灌裝ChoiceBox JavaFX中

我只是在SceneBuilder中設計了一個ChoiceBox,我有一個Person類與我的數據。

public class Person{ 
    private final StringProperty firstName; 

    public Person(){ 
     this(null); 
    } 

    public Person(String fname){ 
     this.firstName = new SimpleStringProperty(fname); 
    } 

    public String getFirstName(){ 
     return this.firstName.get(); 
    } 

    public void setFirstName(String fname){ 
     this.firstName.set(fname); 
    } 

    public StringProperty firstNameProperty(){ 
     return this.firstName; 
    } 
} 

在主類中,我有:

private ObservableList<Person> personList = FXCollections.observableArrayList(); 
this.personList.add(new Person("Human1")); 

RootController controller = loader.getController(); 
     controller.setChoiceBox(this); 

public ObservableList<Person> getPersonList(){ 
    return this.personList; 
} 

而且在我的控制器:

public class RootController { 
    @FXML 
    private ChoiceBox personBox; 

    public RootController(){ 

    } 

    @FXML 
    private void initialize(){ 

    } 

    public void setChoiceBox(App app){ 

     personBox.setItems(app.getPersonList()); 
    } 


} 

但這個代碼由函數名(?)或類似的東西填補我ChoiceBox。 我怎麼能與firstName屬性補嗎?

回答

0

對於你的問題,我建議使用「最簡單的way'.The ChoiceBox使用類導致類似[email protected]toString()方法。

通過重寫toString()方法,你可以定義ChoiceBox將顯示的內容。你的情況返回firstName屬性的值:你已經通過使firstName財產可變這裏創建自己的一個大問題

@Override 
public String toString() { 
    return firstName.get(); 
} 
1

注意。我們不可能讓ChoiceBox傾聽對該財產的修改(至少在沒有更換skin的情況下,這將非常複雜)。

這可能與一但被ComboBox完成。

你只需要使用自定義cellFactory

private ListCell<Person> createCell(ListView<Person> listView) { 
    return new ListCell<Person>() { 

     @Override 
     protected void updateItem(Person item, boolean empty) { 
      super.updateItem(item, empty); 

      if (empty || item == null) { 
       textProperty().unbind(); 
       setText(""); 
      } else { 
       textProperty().bind(item.firstNameProperty()); 
      } 
     } 

    }; 
} 
ComboBox<Person> cb = new ComboBox<>(personList); 
cb.setCellFactory(this::createCell); 
cb.setButtonCell(createCell(null)); 
... 
+0

我完全@fabian但對我來說,問題是爲什麼以及何時一個人的名字真正的改變?編輯:給予好評的提示 – SSchuette