Show a column with String in table view where the field of the model class is Boolean - javafx

Asked

Viewed 18 times

0

Good afternoon, you guys!

I am studying javafx and I am creating a simple application, I was doing well until I came across the following problem: I have a model class 'User' that may or may not have administrator privilege, the problem occurs when I list users in a table view I would like to have "YES" or "NO" appear in the corresponding field column instead of true/false. I tried by toString() model class but it didn’t work, follows the table image: A coluna ADM quero que apareça sim ou não

my code that loads the table:

        public void carregarTabela(List<Usuario> usuarios) {
        
        colUser.setCellValueFactory(new PropertyValueFactory<Usuario, String>("user"));
        colSenha.setCellValueFactory(new PropertyValueFactory<Usuario, String>("senha"));               
        colAdm.setCellValueFactory(new PropertyValueFactory<Usuario,String >("admin"));
        tabelaUsuarios.getItems().setAll(usuarios);             
    }

Below the toString of the model class:

    @Override
public String toString() {
    String admin = null;
    if(isAdmin()) {
        admin="SIM";
    }admin="NÃO";
    return "Usuario [user=" + user + ", senha=" + senha + ", admin=" + admin + "]";
}

From now on I thank anyone who can help me!

1 answer

0


Using the cellfactory in the desired column

@FXML
private TableColumn<Usuario, Boolean> colAdm;


colAdm.setCellFactory(new Callback<TableColumn<Usuario, Boolean>, 
    TableCell<Usuario, Boolean>>() {
        @Override
        public TableCell<Usuario, Boolean> call(TableColumn<Usuario, Boolean> tableColumn) {
            return new TableCell<>() {
                @Override
                protected void updateItem(Boolean item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        setText(null);
                        setGraphic(null);
                    } else {
                        Usuario usuario = getTableRow().getItem();
                        if(usuario != null) {
                            setText(usuario.isAdmin() ? "SIM" : "NÃO");
                        } else {
                            setText(null);
                            setGraphic(null);
                        }
                    }
                }
            };
        }
    });
  • Cassio, thank you so much! That’s just what I needed!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.