简体   繁体   English

更改 javaFX 中的特定行颜色

[英]Change specific row color in javaFX

Here is the code i write to change row color where leather's meter < 200 but i face null pointer exception in if condition.这是我编写的代码,用于更改皮革米 < 200 的行颜色,但在 if 条件下我面临 null 指针异常。 First i get all data from database and add them all to table view so i don't expect null pointer exception.首先,我从数据库中获取所有数据并将它们全部添加到表视图中,所以我不希望 null 指针异常。 What is the problem?问题是什么?

    @FXML
    TableView<Leather> tableView;
    ObservableList<Leather> data = FXCollections.observableArrayList();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tableView.setEditable(true);
        codeCol.setCellValueFactory(new PropertyValueFactory<>("code"));
        colorCol.setCellValueFactory(new PropertyValueFactory<>("color"));
        meterCol.setCellValueFactory(new PropertyValueFactory<>("meter"));

        indexCol.setCellFactory(col -> new TableCell<Task, String>() {
            @Override
            public void updateIndex(int index) {
                super.updateIndex(index);
                if (isEmpty() || index < 0) {
                    setText(null);
                } else {
                    setText(Integer.toString(index+1));
                }
            }
        });

        data.addAll(storeService.getAll());
        tableView.setItems(data);

        tableView.setRowFactory(tv -> new TableRow<Leather>(){
            @Override
            protected void updateItem(Leather item, boolean empty) {
                super.updateItem(item,empty);
                if (item.getMeter()<200){
                    setStyle("-fx-background-color: #DB8A6B");
                }
            }
        });
     }

You need to handle all cases in your rowFactory (in the same way you do in your cellFactory ):您需要处理 rowFactory 中的所有情况(与您在rowFactory中的处理方式cellFactory ):

    tableView.setRowFactory(tv -> new TableRow<Leather>(){
        @Override
        protected void updateItem(Leather item, boolean empty) {
            super.updateItem(item,empty);
            if (empty || item == null) {
                setStyle("");
            } else if (item.getMeter()<200){
                setStyle("-fx-background-color: #DB8A6B");
            } else {
                setStyle("");
            }
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM