fiman
fiman

Reputation: 13

Marking TableView's row by mouse click

I am trying to create editable panel for a day schedule. I created TableView with 24 rows, which representing hours. Now i would like to mark each hours by mouse click and i stuck with that.

Upvotes: 1

Views: 554

Answers (1)

Manuel Seiche
Manuel Seiche

Reputation: 221

I'm not sure, whether I understood your question, but if you want to let a TableRow react on MouseClicks you could do it this way:

(You could possibly also add a listener to the TableViews selectionModel, this is just one approach of many)

@Override
public void start(Stage primaryStage) throws Exception {
    TableView<String> table = new TableView<String>();
    // Add rows
    for (int hour = 1; hour <= 24; hour++) {
        table.getItems().add(String.valueOf(hour));
    }
    TableColumn<String, String> tableColumn = new TableColumn<String, String>("Hours");
    // We only show Text
    tableColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue()));
    table.getColumns().add(tableColumn);
    // Stretch column to tableViews width
    table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    // We create our own TableRows and listen on Clicks. You could also add
    // a listener to the tableViews selectionModel, but I like this way
    // more.
    table.setRowFactory(tableView -> {
        TableRow<String> row = new TableRow<String>();
        // If a row of our table is clicked...
        row.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent mouseEvent) {
                // If not already applied we add a css-class defined 
                // in style.css.
                if (!row.getStyleClass().contains("marked")) {
                    row.getStyleClass().add("marked");
                }
                // ... 
            }
        });
        return row;
    });
    // The uninteresting stuff...
    Scene scene = new Scene(table, 50, 600);
    scene.getStylesheets()
            .add(getClass().getResource("/com/stackoverflow/marktablerows/style.css").toExternalForm());
    primaryStage.setScene(scene);
    primaryStage.show();
}

And com/stackoverflow/marktablerows/style.css:


    .marked{
        -fx-background-color:linear-gradient(to right, lightblue, blue);
        -fx-background-radius:10px;
        -fx-font-weight:bold;
    }

Image

edit: Take a look at Programmatically change the TableView row appearance

Upvotes: 1

Related Questions