Jump to content
Fórum Script Brasil
  • 0

Problema ao selecionar duas tabelas em um código java


celomorais

Question

Ae galerinha, gostaria de um help, tenho o código abaixo, e duas tabelas no meu mysql (Clientes com os campos id, nome e telefone, Encomendas com os campos encomenda, quantidade e data), no java tenho o jframe para consultar clientes e suas respectivas encomendas, porém no jframe eu adicionei uma tabela o "jtable" para poder lista as encomendas daquele clientes, quando iniciou o código ele seleciona a tabela cliente, dai eu posso preencher no campo de texto o nome e o telefone, o problema é que quando vou selecionar as encomendas daquele cliente, preciso selecionar a tabela encomendas e não consigo preencher a "jtable" no jframe

segue o código

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Consulta.java
 *
 * Created on 20/03/2011, 10:55:03
 */

package consultas;

import TelaPrincipal.TelaPrincipal;
import utilitarios.conexao;
import javax.swing.*;
import java.sql.*;
import javax.swing.table.DefaultTableModel;


/**
 *
 * @author CeLo
 */
public class Consulta extends javax.swing.JFrame {
     int navega = 0; //apenas para sabermos em qual botao foi clicado
     conexao consulta;
    private Connection conexao;

    /** Creates new form Consulta */
    public Consulta() {
        initComponents();
        consulta =  new conexao();
        consulta.conecta();
        consulta.executeSQL("select * from clientes");
        campo_codigo.setEditable(false);
        campo_nome.setEditable(false);
        campo_telefone.setEditable(false);
            

    }

    /** 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() {

        titulo = new javax.swing.JLabel();
        nome = new javax.swing.JLabel();
        telefone = new javax.swing.JLabel();
        campo_nome = new javax.swing.JTextField();
        campo_telefone = new javax.swing.JTextField();
        voltar = new javax.swing.JButton();
        primeiro = new javax.swing.JButton();
        anterior = new javax.swing.JButton();
        proximo = new javax.swing.JButton();
        ultimo = new javax.swing.JButton();
        excluir = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        codigo = new javax.swing.JLabel();
        campo_codigo = new javax.swing.JTextField();
        botao_editar = new javax.swing.JButton();
        botao_ok = new javax.swing.JButton();
        botao_pesquisa = new javax.swing.JButton();
        campo_pesquisa = new javax.swing.JTextField();
        pesquisa = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("CONSULTA DE CLIENTES");

        titulo.setFont(new java.awt.Font("Copperplate Gothic Bold", 1, 14)); // NOI18N
        titulo.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\hamburg\\customers.png")); // NOI18N
        titulo.setText("CONSULTA DE CLIENTES");

        nome.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 12));
        nome.setText("Nome:");

        telefone.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 12));
        telefone.setText("Tel.:");

        voltar.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\http___iconesbr.oficinadanet.com_7000_32x32.png")); // NOI18N
        voltar.setText("VOLTAR");
        voltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                voltarActionPerformed(evt);
            }
        });

        primeiro.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\first.png")); // NOI18N
        primeiro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                primeiroActionPerformed(evt);
            }
        });

        anterior.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\http___iconesbr.oficinadanet.com_7856_32x32.png")); // NOI18N
        anterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                anteriorActionPerformed(evt);
            }
        });

        proximo.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\http___iconesbr.oficinadanet.com_7854_32x32.png")); // NOI18N
        proximo.setMinimumSize(new java.awt.Dimension(119, 41));
        proximo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                proximoActionPerformed(evt);
            }
        });

        ultimo.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\last.png")); // NOI18N
        ultimo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ultimoActionPerformed(evt);
            }
        });

        excluir.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\http___iconesbr.oficinadanet.com_3576_32x32.png")); // NOI18N
        excluir.setText("EXCLUIR");
        excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                excluirActionPerformed(evt);
            }
        });

        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "Encomenda", "Quantidade", "Data"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabela.setEnabled(false);
        tabela.setPreferredSize(new java.awt.Dimension(300, 160));
        jScrollPane1.setViewportView(tabela);
        tabela.getColumnModel().getColumn(0).setResizable(false);
        tabela.getColumnModel().getColumn(0).setPreferredWidth(20);
        tabela.getColumnModel().getColumn(1).setResizable(false);
        tabela.getColumnModel().getColumn(1).setPreferredWidth(20);
        tabela.getColumnModel().getColumn(2).setResizable(false);
        tabela.getColumnModel().getColumn(2).setPreferredWidth(10);

        codigo.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 12));
        codigo.setText("Registro:");

        botao_editar.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\cologne\\edit.png")); // NOI18N
        botao_editar.setText("EDITAR ");
        botao_editar.setMaximumSize(new java.awt.Dimension(117, 41));
        botao_editar.setMinimumSize(new java.awt.Dimension(117, 41));
        botao_editar.setPreferredSize(new java.awt.Dimension(117, 41));
        botao_editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botao_editarActionPerformed(evt);
            }
        });

        botao_ok.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\cologne\\check.png")); // NOI18N
        botao_ok.setText("OK");
        botao_ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botao_okActionPerformed(evt);
            }
        });

        botao_pesquisa.setIcon(new javax.swing.ImageIcon("D:\\JAVA\\imagens\\cologne\\search.png")); // NOI18N
        botao_pesquisa.setText("PESQUISAR");
        botao_pesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botao_pesquisaActionPerformed(evt);
            }
        });

        pesquisa.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 12));
        pesquisa.setText("PESQUISA:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(voltar)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(codigo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(campo_codigo, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGap(59, 59, 59)
                        .addComponent(titulo)
                        .addGap(121, 121, 121))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(primeiro)
                        .addGap(18, 18, 18)
                        .addComponent(anterior)
                        .addGap(18, 18, 18)
                        .addComponent(proximo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(ultimo)
                        .addGap(18, 18, 18)
                        .addComponent(excluir))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(pesquisa)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(campo_pesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botao_pesquisa)
                        .addContainerGap(92, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(telefone)
                            .addComponent(nome))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(campo_telefone, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botao_editar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botao_ok))
                            .addComponent(campo_nome, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(54, 54, 54))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(voltar)
                    .addComponent(titulo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(pesquisa)
                            .addComponent(campo_pesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(campo_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(codigo)))
                    .addComponent(botao_pesquisa))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nome)
                    .addComponent(campo_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(telefone)
                        .addComponent(campo_telefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(botao_editar, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                        .addComponent(botao_ok, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ultimo)
                    .addComponent(proximo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(anterior)
                    .addComponent(primeiro)
                    .addComponent(excluir))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-490)/2, (screenSize.height-483)/2, 490, 483);
    }// </editor-fold>                        

    private void proximoActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try
        {

            consulta.resultset.next();
            mostra_dados();
            navega = 2;
        }
        catch(SQLException erro)
        {
            JOptionPane.showMessageDialog(null,"Não possível ir para o próximo" +
                    "registro" + erro);
        }
    }                                       

    private void primeiroActionPerformed(java.awt.event.ActionEvent evt) {                                         
try
        {

            consulta.resultset.first();
            mostra_dados();
            
        }
        catch(SQLException erro)
        {
            JOptionPane.showMessageDialog(null,"Não foi possível ir para o primeiro" +
                    "registro" + erro);
        }
    }                                        

    private void ultimoActionPerformed(java.awt.event.ActionEvent evt) {                                       
   try
        {

            consulta.resultset.last();
            mostra_dados();
            
        }
        catch(SQLException erro)
        {
            JOptionPane.showMessageDialog(null,"Não foi possível ir para o último" +
                    "registro" + erro);
        }
    }                                      

    private void anteriorActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try
        {

            consulta.resultset.previous();
            mostra_dados();
            navega = 1;
        }
        catch(SQLException erro)
        {
            JOptionPane.showMessageDialog(null,"Não foi possível ir para o registro " +
                    "anterior" + erro);
        }
    }                                        

    private void excluirActionPerformed(java.awt.event.ActionEvent evt) {                                        
        try {
            String sql = "select * from clientes Where id = "+campo_codigo.getText();
            consulta.executeSQL(sql);
            consulta.resultset.first();
            String nome1 = "Deletar " + consulta.resultset.getString("nome")+" ?";
            int opcao_escolhida = JOptionPane.showConfirmDialog(null,nome1,"Exclusão ",JOptionPane.YES_NO_OPTION);
            if (opcao_escolhida == JOptionPane.YES_OPTION) {

                sql = "DELETE FROM clientes Where id =" +campo_codigo.getText();
                int conseguiu_excluir = consulta.statement.executeUpdate(sql);
                if (conseguiu_excluir == 1) {
                    JOptionPane.showMessageDialog(null, "Exclusão realizada com sucesso");
                    //Atualizado o resultset
                    consulta.executeSQL("Select * from clientes");
                    consulta.resultset.first();
                    mostra_dados();
                }
            } else
                return;
        } catch(SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao tentar excluir registro" + erro);
        }
    }                                       

    private void voltarActionPerformed(java.awt.event.ActionEvent evt) {                                       
        new TelaPrincipal().setVisible(true);
        dispose();
    }                                      

    private void botao_editarActionPerformed(java.awt.event.ActionEvent evt) {                                             

    campo_nome.setEditable(true);
    campo_telefone.setEditable(true);

    }                                            

    private void botao_okActionPerformed(java.awt.event.ActionEvent evt) {                                         
try
{
    String sql = "UPDATE clientes SET nome ='"+campo_nome.getText()+"',"+
            "telefone = '"+campo_telefone.getText()+"' where id = " +campo_codigo.getText();
    consulta.statement.executeUpdate(sql);
    JOptionPane.showMessageDialog(null, "Alteração realizada com sucesso");

    //atualiza o resultset
    consulta.executeSQL("Select * from clientes");
    consulta.resultset.first();
    campo_nome.setEditable(false);
    campo_telefone.setEditable(false);
    mostra_dados();
}
catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao tentar ediatr registro" + erro);
        }

    }                                        

    private void botao_pesquisaActionPerformed(java.awt.event.ActionEvent evt) {                                               
try
{
   consulta.resultset.first();
   String igual = "n";
   int tamanho_pesquisa = campo_pesquisa.getText().length();
   while(   igual.equals("n"))
   {
       String pesquisado = consulta.resultset.getString("nome").substring(0,(tamanho_pesquisa));

       if(pesquisado.equals(campo_pesquisa.getText()))
       {
           igual = "s";
       }
       else
           consulta.resultset.next();
   }
   campo_codigo.setText(consulta.resultset.getString("id"));
   mostra_dados();
}
catch(SQLException erro)
{
      JOptionPane.showMessageDialog(null, "Não foi possível localizar registro" + erro);
}
    }                                              

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Consulta().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton anterior;
    private javax.swing.JButton botao_editar;
    private javax.swing.JButton botao_ok;
    private javax.swing.JButton botao_pesquisa;
    private javax.swing.JTextField campo_codigo;
    private javax.swing.JTextField campo_nome;
    private javax.swing.JTextField campo_pesquisa;
    private javax.swing.JTextField campo_telefone;
    private javax.swing.JLabel codigo;
    private javax.swing.JButton excluir;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel nome;
    private javax.swing.JLabel pesquisa;
    private javax.swing.JButton primeiro;
    private javax.swing.JButton proximo;
    private javax.swing.JTable tabela;
    private javax.swing.JLabel telefone;
    private javax.swing.JLabel titulo;
    private javax.swing.JButton ultimo;
    private javax.swing.JButton voltar;
    // End of variables declaration                   

    public void mostra_dados()
    {
        try
        {
        
        campo_nome.setText(consulta.resultset.getString("nome"));
        campo_telefone.setText(consulta.resultset.getString("telefone"));
        campo_codigo.setText(consulta.resultset.getString("id"));
        tabela.enable(false);
        preencher_tabela();
        
            
        }
        catch(SQLException erro)
        {
            if (navega == 1)
            {
                JOptionPane.showMessageDialog(null,"Você já está no primeiro registro");
            }
            else if(navega == 2)
            {
                JOptionPane.showMessageDialog(null, "Você já está no último registro");
            }
            else
            {
            JOptionPane.showMessageDialog(null,"Não localizou os dados" + erro);
            }
            navega = 0;
         }
    }

      public void preencher_tabela()
    {        
          tabela.getColumnModel().getColumn(0).setPreferredWidth(20);
          tabela.getColumnModel().getColumn(1).setPreferredWidth(20);
          tabela.getColumnModel().getColumn(2).setPreferredWidth(10);

          DefaultTableModel modelo = (DefaultTableModel)tabela.getModel();
          modelo.setNumRows(0);
        
          try
          {        
          //if(consulta.resultset.getString("nome").equals(campo_nome.getText()))
          //while(consulta.resultset.next())
          modelo.addRow(new Object[]{consulta.resultset.getString("Nome"),consulta.resultset.getString("Telefone")});
          }
          catch(SQLException erro)
          {
              JOptionPane.showMessageDialog(null, "Erro ao listar na tabela");
          }
      }
}

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.2k
    • Total Posts
      652k
×
×
  • Create New...