JAVAFX TableView CELL should display text in multiline in single cell with multi color. possible?

后端 未结 2 774
别跟我提以往
别跟我提以往 2021-01-15 10:28

I need to have TableView CELL should display text in multi line in single cell with multi color.

In CELL I am displaying Multiline text using \"\\n\" currently. But

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-15 10:48

    You can use a cellFactory to customize the way the content is displayed. Assuming the values for the column are Strings like "Charlotte\n403 St. Tryon Street" and "Tony Stark\n10880 Malibu Point\n90265"

    It could be done like this:

    column.setCellFactory(tv -> new TableCell() {
    
        private final VBox lines;
    
        {
            lines = new VBox();
            lines.getStyleClass().add("address");
            setGraphic(lines);
        }
    
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
    
            lines.getChildren().clear();
    
            if (!empty && item != null) {
                int lineNo = 1;
                for (String line : item.split("\n")) {
                    Text text = new Text(line);
                    text.getStyleClass().add("line-" + (lineNo++));
                    lines.getChildren().add(text);
                }
            }
        }
    
    });
    

    CSS stylesheet

    .address > * {
        -fx-fill: green;
    }
    
    .address > .line-1 {
        -fx-fill: red;
    }
    

    Note that this uses CSS to style the lines, but you could also assign the color in the updateItem method directly...

提交回复
热议问题