JavaFX – Change ListView's FocusModel

I have a ListView and am currently overriding the SelectionModel to prevent selection of the items, but when you attempt to select an item, it is still showing the outline.

Reading over the API, I found that I can do the same thing but this time by overriding the FocusModel using

    listView.setFocusModel(new SettingsFocusModel<VBox>()); 

And here is my SettingsFocusModel

public class SettingsFocusModel<T> extends FocusModel<T> {     @Override     protected int getItemCount() {         return 0;     }      @Override     protected T getModelItem(int index) {         return null;     } } 

It is not working as intended, though. I can still see the outline as if I did not override the FocusModel. Any help is appreciated!

Add Comment
2 Answer(s)

You can change your ListView CSS to prevent this:

import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ListView; import javafx.scene.layout.VBox; import javafx.stage.Stage;  public class HelloFX extends Application {      @Override     public void start(Stage stage) {         ListView<String> listView = new ListView<>();         listView.getStyleClass().add("list-view-unselect");         listView.getItems().add("Item 1");         listView.getItems().add("Item 2");         listView.getItems().add("Item 3");          VBox vbox = new VBox(listView);         Scene scene = new Scene(vbox, 640, 480);         scene.getStylesheets().add("style.css");         stage.setScene(scene);         stage.setTitle("JavaFX App");         stage.show();      }      public static void main(String[] args) {         launch();     } } 

And style.css:

.list-view-unselect .list-cell:filled:selected:focused, .list-view-unselect .list-cell:filled:selected {     -fx-background-color: white;     -fx-text-fill: black; }  .list-view-unselect .list-cell:even {     -fx-background-color: white;     -fx-text-fill: black; } .list-view-unselect .list-cell:odd {     -fx-background-color: white;     -fx-text-fill: black; } 
Add Comment

For my specific case, I ended up doing the following:

listView.setSelectionModel(new SettingsSelectionModel<VBox>()); listView.getStyleClass().add("settings-view"); 

SettingsSelectionModel follows the following answer: https://stackoverflow.com/a/46186195/7987450

My css file includes:

    .list-view:focused > .virtual-flow > .clipped-container > .sheet > .list-cell:focused {     -fx-background-color: null; }  .list-view:focused > .virtual-flow > .clipped-container > .sheet > .list-cell:hover {     -fx-background-color: null; }  .list-view:focused > .virtual-flow > .clipped-container > .sheet > .list-cell:filled:selected {     -fx-background-color: null; } 

I chose to set the background color to null each time because this works in both Dark and Light modes.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.