Display date correctly on a Jtable

Asked

Viewed 443 times

0

I am unable to display the sql database date type Date in Jtable, the date appears that way:

inserir a descrição da imagem aqui

I use the following method to call the table data:

public ArrayList<Alunos> read(){
    PreparedStatement stmt = null;
    ResultSet rs = null;

    ArrayList <Alunos> aluno = new ArrayList();

    try {
        stmt = connection.prepareStatement("select * from alunos");
        rs = stmt.executeQuery();//guarda os resultados do select no rs

        while(rs.next()){ //enquanto o select gerar valor, o while será executado
            Alunos alu = new Alunos();

            //Date data =  (Date) alu.getDataNascimento().getTime();
            alu.setId(rs.getInt("id"));//nome da coluna onde será mostrado 
            alu.setNome(rs.getString("nome"));
            alu.setCpf(rs.getString("cpf"));
            alu.setRg(rs.getString("rg"));
            alu.setEndereco(rs.getString("endereco"));
            alu.setEstado(rs.getString("estado"));
            alu.setDataNascimento(toCalendar(rs.getDate("nasc")));
            aluno.add(alu);

        }
        stmt.close();
        rs.close();

    } catch (SQLException ex) {
        Logger.getLogger(AlunoDao.class.getName()).log(Level.SEVERE, null, ex);
    }
    return aluno;
}

public static Calendar toCalendar(Date date){ 
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    return cal;
}

And this is where I call the method in JPanel:

public void readJTable(){//lê os dados para tabela
   DefaultTableModel modelo = (DefaultTableModel) jTAlunos.getModel();

   AlunoDao aluDao = new AlunoDao();

   for(Alunos a: aluDao.read()){///adiciona linha na tabela
       modelo.addRow(new Object[]{
           a.getId(),
           a.getNome(),
           a.getCpf(),
           a.getRg(),
           a.getEndereco(),
           a.getEstado(),
           a.getDataNascimento().toString()
       });
   }
}

This is the class where I keep the data:

import java.util.Calendar;

public class Alunos {
private int id;
private String nome;
private String cpf;
private String rg;
private String endereco;
private String estado;
private Calendar dataNascimento;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getCpf() {
    return cpf;
}

public void setCpf(String cpf) {
    this.cpf = cpf;
}

public String getRg() {
    return rg;
}

public void setRg(String rg) {
    this.rg = rg;
}

public String getEndereco() {
    return endereco;
}

public void setEndereco(String endereco) {
    this.endereco = endereco;
}

public String getEstado() {
    return estado;
}

public void setEstado(String estado) {
    this.estado = estado;
}

public Calendar getDataNascimento() {
    return dataNascimento;
}

public void setDataNascimento(Calendar dataNascimento) {
    this.dataNascimento = dataNascimento;
}

}

  • Carlos, provide a [mcve] so that it is possible to test the code and propose a solution.

2 answers

4


The ideal solution would be to use date class in the class Alunos, because it makes no sense to use Calendar to store a "date of birth". I don’t know if you have a good reason for this, but I recommend reviewing your modeling.

Using SimpleDateFormat you will not be able to format a type Calendar, as suggested in the other reply. Just a quick query in the method documentation SimpleDateFormat#format() to see that he’s expecting a guy Date.

Even changing the type to Date, to avoid gambiarras in the exhibition of JTable, you should create a redenderer(examples here and here) to the column, but as wrote a Tablemodel, makes it even more difficult to apply it to table or suggest a Renderer.

I recommend you take a deals with how to create a Tablemodel, because it can make it easier to expand functionality to your table without having to write an unnecessary code template like this loop you’re using to fill it. I also recommend that you read about new date classes of java, given that both Calendar as to the class itself Date has some problems that have been fixed by adding the new classes next to java 8.

Assuming that, after all that has been said above, you still have a good reason to keep the implementation the way it is, the perhaps simplest solution(but it doesn’t mean it’s good) is to get the Calendar Date type through the method getTime() and apply the formatter then inside the loop:

for (Alunos a : aluDao.read()) {/// adiciona linha na tabela
    modelo.addRow(new Object[] { 
            a.getId(), 
            a.getNome(), 
            a.getCpf(), 
            a.getRg(), 
            a.getEndereco(), 
            a.getEstado(),
            new SimpleDateFormat("dd/MM/yyyy").format(a.getDataNascimento().getTime()) 
    });
}
  • Thank you very much, I am beginner in java, but I will search everything you said.

-1

I think you just need to format the date, doing so:

 SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");

 for(Alunos a: aluDao.read()){///adiciona linha na tabela
   modelo.addRow(new Object[]{
       a.getId(),
       a.getNome(),
       a.getCpf(),
       a.getRg(),
       a.getEndereco(),
       a.getEstado(),
       formatter.format(a.getDataNascimento())
   });
}

I’m not sure it works with the Calendar guy.

  • Iago, have you even tested? This code won’t even compile.

Browser other questions tagged

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