Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

How to change the background color of a row when you have cell selection in tableview?

2622424Mar 10 2014 — edited Mar 10 2014

I have a tableview and I have selected cell selection.How could I change the backround color of a row if I select a cell?

This post has been answered by James_D on Mar 10 2014
Jump to Answer

Comments

James_D

table.setStyle("-fx-selection-bar: green;");


2622424

This changes the backgroung color of the cell which is selected.I want if it is possible to draw the background color of the row of which the cell is selected.

James_D

Ah, OK, I get what you're asking now.

I can't see an elegant way to do this. I think you have to observe the selection model's selected cells list, and when it changes update a set of selected row indexes. Create a custom TableRow for the table, which observes the set of selected row indexes and updates the style class of the row accordingly. If you are using JavaFX 8, you can use pseudoclass state on the table rows, which makes it a bit cleaner. I can probably throw some sample code together if you need, but let me know which JavaFX version you are working with.

MoC

.table-view:focused .table-row-cell:selected {

    -fx-background-color: red;

    -fx-table-cell-border-color: red;

}

James_D

That doesn't work with

table.getSelectionModel().setCellSelectionEnabled(true);

does it?

2622424

As James_D said it doesn't work with cell selection enabled.

2622424

I use JavaFX8 so if you can show a little sample code, it will be the best.

James_D
Answer

Using the usual example:

import javafx.application.Application;

import javafx.beans.binding.Bindings;

import javafx.beans.binding.BooleanBinding;

import javafx.beans.property.SimpleStringProperty;

import javafx.beans.property.StringProperty;

import javafx.collections.FXCollections;

import javafx.collections.ListChangeListener.Change;

import javafx.collections.ObservableList;

import javafx.collections.ObservableSet;

import javafx.css.PseudoClass;

import javafx.geometry.Insets;

import javafx.scene.Group;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.control.SelectionMode;

import javafx.scene.control.TableColumn;

import javafx.scene.control.TablePosition;

import javafx.scene.control.TableRow;

import javafx.scene.control.TableView;

import javafx.scene.control.cell.PropertyValueFactory;

import javafx.scene.layout.VBox;

import javafx.scene.text.Font;

import javafx.stage.Stage;

public class RowHighlightedCellSelectionTableViewSample extends Application {

    public static void main(String[] args) {

        launch(args);

    }

    @Override

    public void start(Stage stage) {

        Scene scene = new Scene(new Group());

        scene.getStylesheets().add(getClass().getResource("selected-row-table.css").toExternalForm());

        stage.setTitle("Table View Sample");

        stage.setWidth(450);

        stage.setHeight(500);

        final Label label = new Label("Address Book");

        label.setFont(new Font("Arial", 20));

        final TableView<Person> table = new TableView<>();

        final ObservableList<Person> data =

            FXCollections.observableArrayList(

                new Person("Jacob", "Smith", "jacob.smith@example.com"),

                new Person("Isabella", "Johnson", "isabella.johnson@example.com"),

                new Person("Ethan", "Williams", "ethan.williams@example.com"),

                new Person("Emma", "Jones", "emma.jones@example.com"),

                new Person("Michael", "Brown", "michael.brown@example.com")

        );

     

        table.getSelectionModel().setCellSelectionEnabled(true);

        table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

     

        final PseudoClass selectedRowPseudoClass = PseudoClass.getPseudoClass("selected-row");

        final ObservableSet<Integer> selectedRowIndexes = FXCollections.observableSet();

        table.getSelectionModel().getSelectedCells().addListener((Change<? extends TablePosition> change) -> {

            selectedRowIndexes.clear();

            table.getSelectionModel().getSelectedCells().stream().map(TablePosition::getRow).forEach(row -> {

                selectedRowIndexes.add(row);

            });

        });

     

        table.setRowFactory(tableView -> {

            final TableRow<Person> row = new TableRow<>();

            BooleanBinding selectedRow = Bindings.createBooleanBinding(() ->

                    selectedRowIndexes.contains(new Integer(row.getIndex())), row.indexProperty(), selectedRowIndexes);

            selectedRow.addListener((observable, oldValue, newValue) ->

                row.pseudoClassStateChanged(selectedRowPseudoClass, newValue)

            );

            return row ;

        });

        TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");

        firstNameCol.setMinWidth(100);

        firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));

        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");

        lastNameCol.setMinWidth(100);

        lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));

        TableColumn<Person, String> emailCol = new TableColumn<>("Email");

        emailCol.setMinWidth(200);

        emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));

     

        table.setItems(data);

        table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);

     

        final VBox vbox = new VBox();

        vbox.setSpacing(5);

        vbox.setPadding(new Insets(10, 0, 0, 10));

        vbox.getChildren().addAll(label, table);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);

        stage.show();

    }

    public static class Person {

        private final StringProperty firstName;

        private final StringProperty lastName;

        private final StringProperty email;

        private Person(String fName, String lName, String email) {

            this.firstName = new SimpleStringProperty(fName);

            this.lastName = new SimpleStringProperty(lName);

            this.email = new SimpleStringProperty(email);

        }

        public String getFirstName() {

            return firstName.get();

        }

        public void setFirstName(String fName) {

            firstName.set(fName);

        }

     

        public StringProperty firstNameProperty() {

            return firstName ;

        }

        public String getLastName() {

            return lastName.get();

        }

        public void setLastName(String fName) {

            lastName.set(fName);

        }

     

        public StringProperty lastNameProperty() {

            return lastName ;

        }

        public String getEmail() {

            return email.get();

        }

        public void setEmail(String fName) {

            email.set(fName);

        }

     

        public StringProperty emailProperty() {

            return email ;

        }

    }

}

And then the selected-row-table.css:

.table-row-cell:selected-row {

    -fx-background-color: lightskyblue ;

}

Marked as Answer by 2622424 · Sep 27 2020
2622424

I try this example but nothing the same background in selection.

James_D

Works fine for me. You included the css file too, right?

When I select a cell, I see the cell in the usual dark blue that a selected cell uses, and the rest of the row is a light blue.

2622424

Yes in the same package.

James_D

It would generate a NullPointerException if it couldn't find the css file (due to the call to toExternalForm()). Check you have the pseudo-class name defined identically: "selected-row" in both the Java code and in the css, and the css class name (".table-row-cell") correct. I have it working nicely.

2622424

You had right I didn't put by mistake to put . in css.Thank you very much.

1 - 13
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Apr 7 2014
Added on Mar 10 2014
13 comments
9,765 views