如何使JavaFX列表视图中的前两行不可选

时间:2014-10-23 05:08:02

标签: java javafx javafx-8

如果我使用playList.getSelectionModel().select(1) - 突出显示的选项将是播放列表的第二行。如果我使用playList.getSelectionModel().select(-1)选择无行(如StackOverflow上其他位置所建议的那样),则会选择第一行。有谁知道为什么这不起作用?我希望listview的前两行永远不会有资格进行选择。

我正在使用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 个答案:

答案 0 :(得分:3)

根据您使用的jdk8的确切(更新)版本,这可能是RT-25679的修复(在RT-38517中部分还原)AFAIK,没有公共API来禁用自动一般来说,聚焦/选择集合视图。只有ListView在其属性中禁用默认行为(未记录!小心,可以更改,恕不另行通知)条目

// 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);