How to make the first 2 rows in a JavaFX listview

2019-09-02 20:20发布

If I use playList.getSelectionModel().select(1) - the highlighted selection will be the second row of the playlist. If I use playList.getSelectionModel().select(-1) to have no rows selected (as suggested elsewhere on StackOverflow) the first row will be selected. Does anyone have any idea of why this is not working? I would like for the first two rows of the listview to never be eligible for selection.

I am using JavaFX-8.

public class AudioPlayerFXMLController implements Initializable {

@FXML
private ListView playList;
private static ObservableList<Object> playListItems;
private static final String NEW_PLAYLIST = "New PlayList";
private static final String FRIEND_PLAYLIST = "Friend's PlayList";

@Override
public void initialize(URL url, ResourceBundle rb) {

    playListItems = FXCollections.observableArrayList();
    playListItems.add(NEW_PLAYLIST);
    playListItems.add(FRIEND_PLAYLIST);

    playList.setItems(FXCollections.observableList(playListItems));


    playList.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
        @Override
        public ListCell<String> call(ListView<String> list) {
            return new ImageCell();
        }
    });

    playList.getSelectionModel().select(-1);

}

static class ImageCell extends ListCell<String> {

    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);

        if ((this.getIndex() == 0) || (this.getIndex() == 1)) {
            ImageView addSymbol;
            addSymbol = ImageViewBuilder.create().image(new Image("/images/ic_add_grey600_15dp.png")).build();
            addSymbol.fitHeightProperty();
            setText(item);
            setGraphic(addSymbol);

        } else {
            setText(null);
            setGraphic(null);
        }
    }

}

}

1条回答
何必那么认真
2楼-- · 2019-09-02 20:44

Depending on which exact (update) version of jdk8 you are using, this might be the fix for RT-25679 (partially reverted in RT-38517) AFAIK, there is no public api to disable the auto-focus/select for the collection views in general. Only ListView has (undocumented! beware, they can change without notice) entries in its properties that disable the default behaviour

// disable selecting the first item on focus gain - this is
// not what is expected in the ComboBox control (unlike the
// ListView control, which does this).
listView.getProperties().put("selectOnFocusGain", false);
// introduced between 8u20 and 8u40b7
// with this, testfailures back to normal
listView.getProperties().put("selectFirstRowByDefault", false);
查看更多
登录 后发表回答