Hi,
I have a ListView with some items, and I want to prevent horizontal scrollbars, i.e. I want to make the listcells have the same width as the ListView. (e.g. if I resize the window, so that my ListView has more width, the ListCell should also take more width).
Text in the list cell should then be displayed with "..." at the end, if there's not enough space.
This is what I got, but I can't make the ListCell's maxWidth work:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TestApp extends Application {
public static void main(String[] args) {
launch();
}
@Override
public void start(final Stage stage) throws Exception {
VBox vBox = new VBox();
ListView<String> listView = new ListView<String>();
listView.setItems(FXCollections.observableArrayList("Short Text", "This is a very long text and should not cause horizontal scrollbars."));
// listView.setMaxWidth(100); ==> no effect on list cells' width
listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> stringListView) {
ListCell<String> listCell = new ListCell<String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(null);
if (!empty) {
setText(item);
}
}
};
listCell.setMaxWidth(100); // has no effect
return listCell;
}
});
vBox.getChildren().add(listView);
Scene scene = new Scene(vBox);
stage.setScene(scene);
stage.show();
}
}