Setar da Tabela para TextFields

9 respostas
rafaelshock

Galera boa tarde, estou com duvida de como fazer
tenho um cadastro de animal, mas nesse cadastro preciso de um cliente e esse cliente vem de uma pesquisa, mas não sei como jogar isso no TextFields?
alguém me ajuda?

desde de já obrigado

9 Respostas

rafaelshock

fiz o metodo de buscar, agora não sei como prosseguir

clienteslistados.clear();
     modelo.setNumRows(0);
     if(txtPesquisa.getText() !=""){
         
         ClienteDAO dao = new ClienteDAO();
         clienteslistados = dao.listarPorNome(txtPesquisa.getText());
         
         for(Cliente u : clienteslistados){
             String[] linha = new String[2];
             
             //linha[0] = u.getCodigo_usuario().toString();
             linha[0] = u.getCodigo_cliente().toString();
             linha[1] = u.getNome();
             
             modelo.addRow(linha);
             
         }
         
        
       tabelapesquisarCliente.setModel(modelo);
         
         
     }else{
         
         JOptionPane.showMessageDialog(this, "Nome de Usuário Invalido");
     }
H

Eu faria da seguinte maneira…
vc provavelmente tem uma lista…
quando vc clica na tabela vc tem uma posicao

eu daria um getLista().getInt(LinhaSelecionadadaTabela).getNome();

rafaelshock

uhum interessante isso, vou procurar saber melhor sobre isso…
valew… :smiley:

rafaelshock

como posso fazer isso?

H

vamos lá!

acredito que vc tenha uma lista…

jtNome.setText(listaPaciente.get(jtTabelaPacientes.getSelectedRow()).getNome());

sacou?

rafaelshock

cara desculpa, mas essa é minha classe pesquisa

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.banhotosa.View;

import br.com.banhotosa.Dao.ClienteDAO;
import br.com.banhotosa.Model.Cliente;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Rafael Almeida
 */
public class FrmPesquisaCliente extends javax.swing.JDialog {
    private List<Cliente> clienteslistados = new ArrayList<Cliente>();
    private DefaultTableModel modelo = new DefaultTableModel();

    /**
     * Creates new form FrmPesquisaUsuario
     */
    public FrmPesquisaCliente(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
         
        JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(12, 38, 587, 230);
		getContentPane().add(scrollPane);

		tabelapesquisarCliente = new JTable();
		scrollPane.setViewportView(tabelapesquisarCliente);

		
		modelo.addColumn("Código Usuário");
		modelo.addColumn("Nome Usuário");

		tabelapesquisarCliente.setModel(modelo);
    }

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

        btPesquisar = new javax.swing.JButton();
        txtPesquisa = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        scrollPane = new javax.swing.JScrollPane();
        tabelapesquisarCliente = new javax.swing.JTable();
        btOk = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        btPesquisar.setText("Pesquisar");
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });

        jLabel1.setText("Nome :");

        tabelapesquisarCliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        scrollPane.setViewportView(tabelapesquisarCliente);

        btOk.setText("Ok");
        btOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btOkActionPerformed(evt);
            }
        });

        btCancelar.setText("Cancelar");
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addGap(21, 21, 21))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btPesquisar))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(127, 127, 127)
                        .addComponent(btOk)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btCancelar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(btPesquisar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 129, Short.MAX_VALUE)
                .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btOk)
                    .addComponent(btCancelar))
                .addContainerGap())
        );

        setBounds(0, 0, 404, 260);
    }// </editor-fold>                        

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

     clienteslistados.clear();
     modelo.setNumRows(0);
     if(txtPesquisa.getText() !=""){
         
         ClienteDAO dao = new ClienteDAO();
         clienteslistados = dao.listarPorNome(txtPesquisa.getText());
         
         for(Cliente u : clienteslistados){
             String[] linha = new String[2];
             
             //linha[0] = u.getCodigo_usuario().toString();
             linha[0] = u.getCodigo().toString();
             linha[1] = u.getNome();
             
             modelo.addRow(linha);
             
         }
         
        
       tabelapesquisarCliente.setModel(modelo);
         
         
     }else{
         
         JOptionPane.showMessageDialog(this, "Nome de Usuário Invalido");
     }
        
        // TODO add your handling code here:
    }                                           

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        setVisible(false);
        
        // TODO add your handling code here:
    }                                          

    private void btOkActionPerformed(java.awt.event.ActionEvent evt) {                                     
       if(tabelapesquisarCliente.getSelectedRow()==-1){
            JOptionPane.showMessageDialog(this, "Selecione um Cliente");
            return;
        }
       
       Cliente cliente = new Cliente();
       cliente.setCodigo(tabelapesquisarCliente.getSelectedRow());
        
       // FrmaddAnimal dialog = new FrmaddAnimal(new javax.swing.JFrame(), true, this,cliente.get(tabelapesquisarCliente.getSelectedRow()));
       // dialog.setVisible(true);
       
       
       
        
        // TODO add your handling code here:
    }                                    

    /**
     * @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(FrmPesquisaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmPesquisaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmPesquisaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmPesquisaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FrmPesquisaCliente dialog = new FrmPesquisaCliente(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btOk;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTable tabelapesquisarCliente;
    private javax.swing.JTextField txtPesquisa;
    // End of variables declaration                   
}
H

e vc pretende colocar os dados ali como? na hora que vc clica no nome ele auto preenche? ou vai querer colocar um boatao para preencher os campos?

rafaelshock

desculpa a demora, para responder então pretendo selecionar e depois tipo um entrer ou dois click para setar na tela de tras…

H

entao, vc clica na tabela, e no keytyped vc coloca

jtNome.setText(listaPaciente.get(jtTabelaPacientes.getSelectedRow()).getNome());
Criado 12 de novembro de 2013
Ultima resposta 18 de nov. de 2013
Respostas 9
Participantes 2