Como Preencher um jtable com dados de 2 tabelas do Mysql

23/07/2015

0

Como eu prenchor os campos de uma jtable com dados de 2 tabelas eu preciso pegar o id do estado que esta com int e transformar ele em seu nome real, tipo na tabela cidade vai ficar assim = idUF = 1; na tabela de estado assim =idUF = Goias;[img:descricao=diagrama do banco de dados]http://arquivo.devmedia.com.br/forum/imagem/400148-20150723-190008.png[/img]


form
public class FrmCadCidades extends javax.swing.JFrame {

    /**
     * Creates new form FrmCadCidades
     */
    public FrmCadCidades() {
        initComponents();

          EstadoDAO dao  = null;  
             try {  
                dao = new EstadoDAO();  
            } catch (SQLException ex) {  
                Logger.getLogger(FrmLogin.class.getName()).log(Level.SEVERE, null, ex);  
                }  

        List<Estado> estados = null;  
            try {  
                estados = dao.lista();  
            } catch (SQLException ex) {  
                    Logger.getLogger(FrmLogin.class.getName()).log(Level.SEVERE, null, ex);  
                }  



        jComboBoxUF.removeAllItems();  
            for (int i = 0; i < estados.size(); i++){  
            jComboBoxUF.addItem(estados.get(i).getNome());  
         }  
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("sisclod?zeroDateTimeBehavior=convertToNullPU").createEntityManager();
        tbCidadeQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT t FROM TbCidade t");
        tbCidadeList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : tbCidadeQuery.getResultList();
        jTextFieldNomeCidade = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxUF = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jButtonSalvar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Cidade..:");

        jComboBoxUF.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel2.setText("UF.:");

        jButtonSalvar.setText("Salvar");
        jButtonSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalvarActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tbCidadeList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("$"));
        columnBinding.setColumnName("Id Cidade");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("$"));
        columnBinding.setColumnName("No Cidade");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("$"));
        columnBinding.setColumnName("Id UF");
        columnBinding.setColumnClass(Integer.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jComboBoxUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldNomeCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(157, 157, 157)
                        .addComponent(jButtonSalvar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(13, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(56, 56, 56)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldNomeCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(jButtonSalvar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(163, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>                        

    private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {                                              
 String nome = jTextFieldNomeCidade.getText();

        //int idUF =Integer.parseInt(jComboBoxUF.toString());
        //int idUF = Integer.parseInt(jComboBoxUF.toString());
        int idUF = jComboBoxUF.getSelectedIndex();

        idUF +=1;
        //Gravar no banco

        Cidade cidade = new Cidade();

        cidade.setNome(nome);
        cidade.setEstado(idUF);

        try{
            CidadeDAO dao = new CidadeDAO();
            dao.gravar(cidade);
        }catch (SQLException e){
            System.out.println("Ocorreu um erro"+e.getMessage());
        }

    }                                             

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmCadCidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmCadCidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmCadCidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmCadCidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmCadCidades().setVisible(true);
            }
        });
    }



public class CidadeDAO {


    Connection conexao = null;

    public CidadeDAO() throws SQLException{
            conexao = Database.getConnection();

    }
                public void gravar(Cidade cidade) throws SQLException{

                    String sql= "insert into tbCidade(noCidade,idUF) values(?,?)";

                        PreparedStatement stmt = conexao.prepareStatement(sql);
                        stmt.setString(1, cidade.getNome());
                        stmt.setInt(2, cidade.getEstado());


                    stmt.execute();
                        stmt.close();
                        System.out.println("Gravado!");
                        conexao.close();
    }




}



/*
 * 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 br.com.sisclod.model;

/**
 *
 * @author adriano
 */
public class Cidade {
    
    private int id;
    private String nome;
    private int estado;

    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 int getEstado() {
        return estado;
    }
    public void setEstado(int estado) {
        this.estado = estado;
    }       
    
}


Eu quero que invés de aparecer a id do estado apareça nome dele.

Agora esta assim:
[img]http://arquivo.devmedia.com.br/forum/imagem/400148-20150723-190352.png[/img]
Adriano Silva

Adriano Silva

Responder

Posts

24/07/2015

Fernando C

Responder

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar