通过鼠标单击标记TableView的行

时间:2016-03-14 14:02:35

标签: java user-interface javafx

我正在尝试为日程安排创建可编辑的面板。我用24行创建了TableView,它代表了几个小时。现在我想用鼠标点击标记每个小时,我坚持使用它。

1 个答案:

答案 0 :(得分:0)

我不确定,我是否理解您的问题,但如果您想让TableRow对MouseClicks做出反应,您可以这样做:

(你也可以在TableViews selectionModel中添加一个监听器,这只是众多方法中的一种)

@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();
}

com / stackoverflow / marktablerows / style.css:


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

Image

编辑:查看Programmatically change the TableView row appearance