[RESOLVIDO]Trazer a Data

13 respostas
rafaelshock

Galera estou tendo duvida em como posso formatar a data ela está vindo na tela assim

como posso arrumar essa data???

13 Respostas

rafaelshock

eita desculpa o tamanho da img… :frowning:

michetti

Posta o código de como você esta recuperando a data e de como você esta colocando na tabela.

rafaelshock

aqui estou inserindo

try {
            Cliente cliente = new Cliente();
            cliente.setNome(txtnome.getText());
            cliente.setCpf(txtCPF.getText());
            cliente.setRg(txtRG.getText());
            cliente.setData_nascimento((Calendar) ((JCalendar) ccbdatanasc).getSelectedItem());
            cliente.setTelefone_casa(txttelefone.getText());
            cliente.setTelefone_celular(txtcelular.getText());
            cliente.setTelefone_outro(txttelrecado.getText());
            cliente.setEmail(txtemail.getText());         
            dao.salvar(cliente);
            controle.setStatus("Cliente Adcionado");
            controle.carregartabela();
            setVisible(false);
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this,"Erro ao adicionar o cliente" + ex, "Adicionar novo cliente",JOptionPane.ERROR_MESSAGE);
            return;
        }

aqui estou mostrando na tabela da tela do cliente

public void carregartabela() {
        try{
        clientes = dao.listar();
         MyTableModel tableModel = new MyTableModel(Cliente.class, clientes, tabelaCliente);
            tabelaCliente.setModel(tableModel);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Erro ao Carregar");
        }

seria isso?

michetti

La no MyTableModelta a parte onde você adciona as linhas, na hora de você usa possivelmente o addRow verifica como você esta a data para tabela.

rafaelshock

tah aqui a classe:

public class MyTableModel extends DefaultTableModel {

    private static final long serialVersionUID = 1L;
    private final List entitysToList;
    private final Class entityClassToList;
    private List<Method> fieldToData = new LinkedList<Method>();
    private final JTable tableToControl;

    /**
     * Construtor padrão
     *
     * @author Dyego Souza do Carmo
     * @version 1.0, 
     */
    public MyTableModel(Class entityClassToList, List entitysToList,JTable tableToControl) {
        super();
        this.entitysToList = entitysToList;
        this.entityClassToList = entityClassToList;
        this.tableToControl = tableToControl;
        try {
            startAddTheColumns();
            startAddValues();
        } catch (Exception ex) {
            Logger.getLogger(MyTableModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    private void startAddTheColumns() throws NoSuchMethodException, InstantiationException, IllegalAccessException {
        // Here is The Reference Class !
        // Reflection is the man !!!!! (or the method ?)
        for (Field field : entityClassToList.getDeclaredFields()) {
            SwingColumn theAnnotation = field.getAnnotation(SwingColumn.class);
            if (theAnnotation != null) {
                // Yes , the column is annotated , but and the next ?
                addColumn(theAnnotation.description());
                //tableToControl.getColumnModel().getColumn(getColumnCount()-1).setCellRenderer(theAnnotation.renderer().newInstance());
                String methodName = "get" + field.getName().toUpperCase().charAt(0) + field.getName().substring(1);
                fieldToData.add(entityClassToList.getDeclaredMethod(methodName));
            }
        }
    }

    private void startAddValues() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        // Manipulates Only the DATA fields

        for (Object entity : entitysToList) {
            List<Object> valuesToAdd = new LinkedList<Object>();

            for (Method method : fieldToData) {
                valuesToAdd.add(method.invoke(entity));
            }

            // Here we add the values in the MODEL !
            addRow(valuesToAdd.toArray());
        }
    }
}
rafaelshock

deixa eu dar mais informações o meotodo que eu uso para trazer na tela é esse...

public void carregartabela() {
        try{
        clientes = dao.listar();
         MyTableModel tableModel = new MyTableModel(Cliente.class, clientes, tabelaCliente);
            tabelaCliente.setModel(tableModel);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Erro ao Carregar");
        }

e o metodo listar da classe ClienteDAO é esse

@SuppressWarnings("unchecked")
	public List<Cliente> listar(){
		EntityManager em = EntityManagerUtil.getEntityManager();
		
		List<Cliente> clientes = new ArrayList<Cliente>();
		try{
			Query query = em.createQuery("from Cliente");
			clientes = query.getResultList();
                        
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			em.close();
		}
		return clientes;
	}
Polverini

No seu addValue verifica se o valor é Date e usa o SimpleDateFormat para converter

rafaelshock

e como faço isso desculpa mas sou novo em java!

H

não achei o codigo da table model… vc ja posto?

michetti

Então cara não tenho certeza mas acho que tem relação com isto aqui

addRow(valuesToAdd.toArray());

Pois a sua data não estar em String, ou algo do tipo, e o toArray() não deve conseguir passar o tipo de variável que é a sua data. Tenta passar a data para string e testa rsrs

rafaelshock

será que é ai mesmo que eu tenho que transforma já???

rafaelshock
himorrivel:
não achei o codigo da table model... vc ja posto?

seria a minha classe modelo????

se for está ai..

public class Cliente {
	

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column
	@NotNull
        @SwingColumn(description="Código",colorOfBackgound="")
	private Integer codigo_cliente;
	@Column
	@NotNull
        @SwingColumn(description="nome",colorOfBackgound="")
	private String nome;
	@Column
        @SwingColumn(description="CPF",colorOfBackgound="")
	private String cpf;
	@Column
        @SwingColumn(description="RG",colorOfBackgound="")
	private String rg;
	@Column
	@Temporal(TemporalType.DATE)
        @SwingColumn(description="Data Nascimento",colorOfBackgound="")
	private Calendar data_nascimento;
	@Column
        @SwingColumn(description="Telefone Residencia",colorOfBackgound="")
	private String telefone_casa;
	@Column
        @SwingColumn(description="Celular",colorOfBackgound="")
	private String telefone_celular;
	@Column
        @SwingColumn(description="Outro Telefone",colorOfBackgound="")
	private String telefone_outro;
	@Column
        @SwingColumn(description="E-mail",colorOfBackgound="")
	private String email;
	
	@OneToMany(mappedBy="codigo_animal")
	private List<Animal>animais = new ArrayList<>();
	
	@OneToMany(mappedBy="codigo_endereco")
	private List<Endereco>enderecos = new ArrayList<>();

        
        
        @Override
          public String toString() {
          return this.getData_nascimento()+" --- "+ this.getNome();   
    }
        
        
     /*  public Cliente (Integer codigo_cliente, String nome, String cpf, String rg, Calendar data_nascimento, 
               String telefone_casa, String telefone_celular, String telefone_outro, String email ) {
        this.codigo_cliente = codigo_cliente;
        this.nome = nome;
        this.cpf = cpf;
        this.rg = rg;
        this.data_nascimento = data_nascimento;
        this.telefone_casa = telefone_casa;
        this.telefone_celular = telefone_celular;
        this.telefone_outro = telefone_outro;
        this.email = email;
    }*/

	public Integer getCodigo_cliente() {
		return codigo_cliente;
	}

	public void setCodigo_cliente(Integer coidgo_cliente) {
		this.codigo_cliente = coidgo_cliente;
	}

	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 Calendar getData_nascimento() {
		return data_nascimento;
	}

	public void setData_nascimento(Calendar data_nascimento) {
		this.data_nascimento = data_nascimento;
	}

	public String getTelefone_casa() {
		return telefone_casa;
	}

	public void setTelefone_casa(String telefone_casa) {
		this.telefone_casa = telefone_casa;
	}

	public String getTelefone_celular() {
		return telefone_celular;
	}

	public void setTelefone_celular(String telefone_celular) {
		this.telefone_celular = telefone_celular;
	}

	public String getTelefone_outro() {
		return telefone_outro;
	}

	public void setTelefone_outro(String telefone_outro) {
		this.telefone_outro = telefone_outro;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public List<Animal> getAnimais() {
		return animais;
	}

	public void setAnimais(List<Animal> animais) {
		this.animais = animais;
	}

	public List<Endereco> getEnderecos() {
		return enderecos;
	}

	public void setEnderecos(List<Endereco> enderecos) {
		this.enderecos = enderecos;
	}

    public void setData_nascimento(String text) {
        this.data_nascimento = data_nascimento;
    }
	
}
rafaelshock

como seria isso que você falou?

Criado 7 de novembro de 2013
Ultima resposta 8 de nov. de 2013
Respostas 13
Participantes 4