silversunhunter
silversunhunter

Reputation: 1269

How can I create a combo box from an object that has an arraylist of objects in javafx?

If I have an object that has an arrayList of objects:

class Event{        
    private ArrayList<Room> rooms;
    //..
    public void setRooms(ArrayList<Room> rooms) {
        this.rooms = rooms;
    }

    public ArrayList<Room> getRooms() {
        return rooms;
    }
}

//---------------------

class Room{
    private String roomId;
    private String roomName;

    public Room(String roomId, String roomName) {
        this.roomId = roomId;
        this.roomName = roomName;
    }

    public String getRoomId() {
        return roomId;
    }

    public String getRoomName() {
         return roomName;
    }

    public void setRoomId(String roomId) {
        this.roomId = roomId;
    }

    public void setRoomName(String roomName) {
         this.roomName = roomName;
    }
}

How can I create a combobox in my table from the array of room objects?

What I have that is only showing an object identifier of some sort.

TableColumn<Event, ArrayList> roomsColumn = new TableColumn<>("Room Select");
roomsColumn.setMinWidth(200);
roomsColumn.setCellValueFactory(new PropertyValueFactory<>("rooms"));

//Create an observable list to populate the table with.
ObservableList<Event> eventList = FXCollections.observableArrayList();

//loop the json to populate the observable list
for (Event event : events.getEventList() ){
   eventList.add(event);
}

//populate the table
eventTable.setItems(eventList);
eventTable.getColumns().addAll(eventColumn, bDateColumn, eDateColumn, roomsColumn);

**All of the columns are built but the rooms column shows a comma separated list of room objects:

com.***.Room@345, com.***.Room@653, com.***.Room@889

Upvotes: 0

Views: 886

Answers (1)

B. Thomas
B. Thomas

Reputation: 201

You need a custom cell factory to return a TableCell with a ComboBox.

    roomsColumn.setCellFactory(call -> {
        // create a new cell for array lists
        return new TableCell<Event, ArrayList<String>>() {
            @Override 
            protected void updateItem(ArrayList<String> item, boolean empty) {
                super.updateItem(item, empty);
                // if there is no item, return an empty cell
                if (empty || item == null) {
                    setGraphic(null);
                } 
                else {
                    ComboBox<String> box = new ComboBox<>();
                    // set combo box items
                    box.setItems(FXCollections.observableArrayList(item));
                    // listen for changes
                    box.valueProperty().addListener((observable, oldValue, newValue) -> {
                        System.out.println("new room "+newValue);
                    });
                    // set cell contents
                    setGraphic(box);
                }
            }
        };
    });

Upvotes: 1

Related Questions