aarexer
aarexer

Reputation: 553

JavaFX listview cell growing

I have problem with showing data using JavaFX lib. Description of my problem: I need to show lists of String's and every list have different count of elements.

All that i invented is create listview for every list. But i have trouble with showing: For example: I have listview with String's - and following simple code for it:

        ListView<String> lst = new ListView<>();
    ObservableList<String> observableList = FXCollections.observableArrayList("Hello", "Hello -2");
    lst.setItems(observableList);
    lst.setPrefHeight(100);
    lst.setOrientation(Orientation.HORIZONTAL);

    Scene scene = new Scene(new VBox(lst));
    primaryStage.setScene(scene);
    primaryStage.show();

And when i run it - i see something like:ListView

But i want that elements in listview fills in space in view, i do not want this stripy space in right side. In my task i have different lists with different count of elements.

If you can help me or get me idea - how it should be done - it will be great!

Thanx!

Upvotes: 0

Views: 431

Answers (1)

Sunflame
Sunflame

Reputation: 3186

I think this is the solution that are you looking for:

public class TestController {

    @FXML
    private ListView<String> listView;

    @FXML
    public void initialize() {
        ObservableList<String> observableList = FXCollections.observableArrayList("Hello", "Hello -2", "More", "Item");
        listView.setItems(observableList);
        listView.setPrefHeight(100);
        Platform.runLater(() -> System.out.println(listView.getWidth()));
        listView.setOrientation(Orientation.HORIZONTAL);
        listView.setCellFactory(param -> new CustomListCell());
    }


    private class CustomListCell extends ListCell<String> {

        CustomListCell() {
            // If you want to use as a separate class you can use the getListView() instead of listView.
            prefWidthProperty().bind(listView.widthProperty()
                    .divide(listView.getItems().size()) // set the width equally for each cell
                    .subtract(1)); // subtracted 1 to prevent displaying of a scrollBar, but you can play with
                                         // this if you have many values in the listView
        }

        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (empty) {
                setText(null);
            } else {
                setText(item);
            }
        }

    }

}

Upvotes: 1

Related Questions