Javafx Tableview apparently takes the value but shows null

Asked

Viewed 1,471 times

2

Hello, I am migrating my program to Javafx to study only, I want to stop using Swing and pass only FX, but as in a previous time I gave up due to my difficulty in Tableview, without delay: I’m having a problem, my code searches the Mysql database with the JDBC drive,and returns the data so I can display them in the table. However, in the table it is "invisible", you can click on the 3 fields of the bank result but it shows nothing. My class Vehicle receiving vehicle data:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com;

import java.util.ArrayList;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;

/**
 *
 * @author Ramon
 */
public class Veiculo {
  private final SimpleStringProperty Marca = new SimpleStringProperty();
  private final SimpleStringProperty Modelo = new SimpleStringProperty();
  private final SimpleStringProperty Cor = new SimpleStringProperty();
  private final SimpleStringProperty Placa = new SimpleStringProperty();
  private final SimpleIntegerProperty idveiculo = new SimpleIntegerProperty();
  private final ArrayList < Veiculo > listaVeiculo;
  public Veiculo(String Marca, String Modelo, String Cor, String Placa) {
    this.Marca.set(Marca);
    this.Modelo.set(Modelo);
    this.Cor.set(Cor);
    this.Placa.set(Placa);
    listaVeiculo = new ArrayList();
  }
  public String getMusica() {
    return Marca.get();
  }

  public String getAlbum() {
    return Modelo.get();
  }

  public String getArtista() {
    return Cor.get();
  }

  public String getGenero() {
    return Placa.get();
  }

  public int getClas() {
    return idveiculo.get();
  }

  public void setMusica(String Marca) {
    this.Marca.set(Marca);
  }

  public void setAlbum(String Modelo) {
    this.Modelo.set(Modelo);
  }

  public void setArtista(String Cor) {
    this.Cor.set(Cor);
  }

  public void setGenero(String Placa) {
    this.Placa.set(Placa);
  }

  public void setClas(int idveiculo) {
    this.idveiculo.set(idveiculo);
  }

  public void adM(Veiculo v) {
    listaVeiculo.add(v);
  }
}

FXML controller where in my opinion the error occurs

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com;

import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;

/**
 * FXML Controller class
 *
 * @author Ramon
 */
public class ExibirVeiculosDentroDaCasaController implements Initializable {@
  FXML private TableColumn clMarca;@
  FXML private TableColumn clModelo;@
  FXML private TableColumn clCor;@
  FXML private TableColumn clPlaca;@
  FXML private TableView < Veiculo > tbVeiculo;
  private ObservableList < Veiculo > listVeiculo;

  /**
   * Initializes the controller class.
   * @param url
   * @param rb
   */
  @
  Override
  public void initialize(URL url, ResourceBundle rb) {
    listVeiculo = FXCollections.observableArrayList();
    assert tbVeiculo != null: "fx:id=\"tableview\" was not injected: check your FXML file 'UserMaster.fxml'.";

    try {
      Class.forName("com.mysql.jdbc.Driver");
      Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bdestacionamento?zeroDateTimeBehavior=convertToNull", "root", "");
      java.sql.Statement st = conn.createStatement();
      ResultSet rs = st.executeQuery("SELECT marca,modelo,cor,placa FROM veiculo,registro WHERE registro.status =1 and registro.veiculo_idveiculo=veiculo.idveiculo ;");
      while (rs.next()) {

        Veiculo v = new Veiculo("1", "2", "3", "4");
        v.setMusica(rs.getString("marca"));
        v.setAlbum(rs.getString("modelo"));
        v.setArtista(rs.getString("cor"));
        v.setGenero(rs.getString("placa"));

        System.out.println(rs.getString("marca"));
        System.out.println(rs.getString("modelo"));
        System.out.println(rs.getString("cor"));
        System.out.println(rs.getString("placa"));
        listVeiculo.add(v);
      }
      clMarca.setCellValueFactory(new PropertyValueFactory("Marca"));
      clModelo.setCellValueFactory(new PropertyValueFactory("Modelo"));
      clCor.setCellValueFactory(new PropertyValueFactory("Cor"));
      clPlaca.setCellValueFactory(new PropertyValueFactory("Placa"));
      tbVeiculo.setItems(null);// Ja pensei que poderia ser isso mas nao é
      tbVeiculo.setItems(listVeiculo);


    } catch (SQLException ex) {
      Logger.getLogger(ExibirVeiculosDentroDaCasaController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
      Logger.getLogger(ExibirVeiculosDentroDaCasaController.class.getName()).log(Level.SEVERE, null, ex);
    }
  }@
  FXML private void btAction() {


  }
}

Does anyone have any notion or hint ? Como podem ver ate a terceira linha da tabela da pra clicar, meio que ele "preencheu" estas linhas, mas não se exibe nada

As you can see up to the third row of the click table, it sort of "filled" these lines, but nothing is shown

1 answer

2


I believe you are not "creating" the table. Try to do the following:

clMarca = new TableColumn<>("Marca");

Do the same for others and then:

tbVeiculo.getColumns().addAll(clMarca, clModelo, clCor, clPlaca);

Edited 04-12-2015

You’re having problems because you’re using SimpleStringProperty. If you give a sysout in your list you will see the way it is displayed. I propose you 2 options:

  1. Make the table based on SimpleStringProperty, then I can’t help you because I don’t know the property, but I found this tutorial.
  2. You can refactor your code to work with the types that package java.lang offers.

Example:

public class Veiculo {
    private String MarcaC;
    private String ModeloC;
    private String CorC;
    private String PlacaC;
    private Integer idveiculo;
    private ArrayList <Veiculo> listaVeiculo;

    //Constructor
    //Get and Set's
}

And in His controller you can do something like this:

public class ExibirVeiculosDentroDaCasaController implements Initializable {
    @FXML
    private TableView<Veiculo> tbVeiculo;

    private List lista;

    /**
     * Initializes the controller class.
     *
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        //Chama o método init ao iniciar o controller
        init();

    }

    //Método que cria as colunas da tabela
    private void init() {
        TableColumn clMarca;
        TableColumn clModelo;
        TableColumn clCor;
        TableColumn clPlaca;

        clMarca = new TableColumn<>("Marca");
        clMarca.setCellValueFactory(new PropertyValueFactory<>("MarcaC"));
        clMarca.setPrefWidth(110);

        clModelo = new TableColumn<>("Modelo");
        clModelo.setCellValueFactory(new PropertyValueFactory<>("ModeloC"));
        clModelo.setPrefWidth(110);

        clCor = new TableColumn<>("Cor");
        clCor.setCellValueFactory(new PropertyValueFactory<>("CorC"));
        clCor.setPrefWidth(110);

        clPlaca = new TableColumn<>("Placa");
        clPlaca.setCellValueFactory(new PropertyValueFactory<>("PlacaC"));
        clPlaca.setPrefWidth(110);
        tbVeiculo.getColumns().addAll(clMarca, clModelo, clCor, clPlaca );

        //Chama o metodo que faz a consulta no banco de dados, se achar melhor pode fazer ele com retorno.
        atualizarTabela();

    }


    //MÉTODO QUE ATUALIZA A TABELA, DESSA FORMA VOCÊ NÃO PRECISARIA MAIS CLICAR EM UM BOTÃO PRA FAZER A CONSULTA.
    private void atualizarTabela() {
        //Inicializa a Lista
        lista = new ArrayList();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bdestacionamento?zeroDateTimeBehavior=convertToNull", "root", "");
            java.sql.Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM veiculo,registro WHERE registro.status =1 and registro.veiculo_idveiculo=veiculo.idveiculo ;");
            while (rs.next()) {
                System.err.println("TESTE");
                Veiculo v = new Veiculo("1", "2", "3", "4");
                v.setMarcaC(rs.getString("marca"));
                v.setModeloC(rs.getString("modelo"));
                v.setCorC(rs.getString("cor"));
                v.setPlacaC(rs.getString("placa"));

                System.out.println(rs.getString("marca"));
                System.out.println(rs.getString("modelo"));
                System.out.println(rs.getString("cor"));
                System.out.println(rs.getString("placa"));
                lista.add(v);
            }
          //Preenche a tabela com os items da lista
           tbVeiculo.setItems(FXCollections.observableArrayList(lista));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I commented on the basics in the code, if you choose the second option and have any questions just ask me.

OBSERVATION: You will need to change some things on your screen if you are not going to use the button don’t forget to delete it. And also delete the table columns as they are being created directly in the code.

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

  • Still gave the same result :(

  • I’ll edit the answer. Just a moment

  • I edited the question, if it doesn’t work I put a complete example for you to try to adapt.

  • Sorry for the delay I ran out of internet there now I’m in college. finally 'clMarca = new Tablecolumn<>("Mark");' was not useful to create more columns in the table, and 'tbVeiculo.getColumns(). addAll(clMarca, clModel, clCor, clPlaca);' of the error when initiating. :(

  • https://github.com/ramonpego/parkingmy git if needed

  • 1

    For you saved me was almost having to go back to SWING, thank you very much.

  • Nothing, man. Javafx is very cool and "attractive". Good luck :D

Show 2 more comments

Browser other questions tagged

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