JavaFX reference a master array list

前端 未结 1 774
星月不相逢
星月不相逢 2021-01-26 18:23

I am writing a mock hotel reservation system with two menus, employee and guest. Created rooms are stored in a master array called roomArray and added to a list view in the empl

相关标签:
1条回答
  • 2021-01-26 18:26

    Since you are using JavaFX, you should use ObservableList for your rooms. Additionally, you would need to use FilteredList and FXCollections.observableArrayList(extractor).

    This is how you can implement it:

    public class Room {
        public enum State {AVAILABLE, BOOKED}
    
        private final ObjectProperty<State> state = new SimpleObjectProperty<>(AVAILABLE);
        public final ObjectProperty<State> stateProperty() { return state; }
        public final State getState() { return state.get(); }
        public final void setState(final State value) { state.set(state); }
    }
    

    Main class:

    private final ObservableList<Room> rooms;
    public final ObservableList<Room> getRooms() { return rooms; }
    
    private final ObservableList<Room> guestRooms;
    public final ObservableList<Room> getGuestRooms() { return guestRooms; }
    
    // Constructor
    public MyClass() {
        rooms = FXCollections.observableArrayList(room -> new Observable[] {room.stateProperty()});
    
        guestRooms = rooms.filtered(room -> room.getState() == Room.State.AVAILABLE);
    }
    

    The guestRooms list is just a wrapper for rooms list, filtered with a Predicate. The filtered list will change according to the rooms list, but it will only react to changes to the list itself (add, remove, replace of elements). To make sure it responds to changes of the state of existing rooms, you need to use FXCollections.observableArrayList(extractor) overload. This overload allows you to control which property in each Room object would also trigger a ListChangeListener.Change, which would also causes the filtered list to update itself.

    0 讨论(0)
提交回复
热议问题