[URGENTE] Ajuda com metodo

6 respostas
T

Amigos tenho um metodo pesquisar (Abaixo):

public Cliente pesquisar (String nome)
    {

        for(int x = 0;x < listaClientes.size();x++){
           Cliente cliente =  (Cliente) listaClientes.get(x);
           Collections.sort(listaClientes);
           if(cliente.getNome().contains(nome))
               return cliente;

        }
        return null;
       }

preciso usalo em um jframe (Abaixo):

package visao;

import controle.ControleCLIENTE;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import modelo.Cliente;
import javax.swing.JOptionPane;

/**
 *
 * @author sala302b
 */
public class Pesquisar extends javax.swing.JFrame {
    private  ControleCLIENTE cliente = null;

    /** Creates new form Pesquisar */
    public Pesquisar() {
        initComponents();
        setLocationRelativeTo(null);
    }
    public Pesquisar(ControleCLIENTE cliente) {
        initComponents();
         setLocationRelativeTo(null);
         this.cliente = cliente;
    }
    /** 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() {

        jPanel1 = new javax.swing.JPanel();
        codigo = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        Consultar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        limpar = new javax.swing.JButton();
        Menu = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("CONSULTA DE CLIENTES");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 0, 255))); // NOI18N

        codigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                codigoActionPerformed(evt);
            }
        });

        jLabel1.setText("Digite o código do Cliente que deseja consultar");

        Consultar.setText("Consultar");
        Consultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConsultarActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        limpar.setText("Limpar");
        limpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                limparActionPerformed(evt);
            }
        });

        Menu.setText("Retornar");
        Menu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(codigo)
                                .addGap(18, 18, 18)
                                .addComponent(Consultar))
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(limpar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Menu)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Consultar)
                    .addComponent(limpar)
                    .addComponent(Menu))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE)
                .addContainerGap())
        );

        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()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

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

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


      
}                                         

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

    private void limparActionPerformed(java.awt.event.ActionEvent evt) {                                       
codigo.setText("");
jTextArea1.setText("");
codigo.requestFocus();        // TODO add your handling code here:
    }                                      

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

 Pesquisar.this.dispose();        // TODO add your handling code here:
    }                                    

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton Consultar;
    private javax.swing.JButton Menu;
    private javax.swing.JTextField codigo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JButton limpar;
    // End of variables declaration                   
  

}

quando digitar o nome no jtextfield o metodo pesquisar traga os dados do cliente e mostre na jtextarea.
Será que alguem pode me ajudar?. ja to a um tempão queimando fosfato com isso.

6 Respostas

josue_carrecon

Cadê o seu bean???

ViniGodoy
1. Você deve definir o tipo da lista de clientes em sua declaração, para evitar ter que fazer casts. Declare-a assim:
List<Cliente> clientes = new ArrayList<Cliente>();

2. Seu método de pesquisa está completamente errado:
- Ele ordena dentro do for, o que é desnecessário;
- Ele retorna null após testar o primeiro cliente, não todos os clientes;
- Ele pode se tornar mais simples se você usar o foreach

O correto é assim:

public Cliente pesquisar (String nome) {
   for (Cliente cliente : listaCliente) {
      if(cliente.getNome().contains(nome)) {
         return cliente;      
      }
   }

   return null;
}

Nem olhei o resto, pois aí pode já estar o problema.

ViniGodoy

Ah sim, e por favor, evite palavras como “URGENTE” e “SOCORRO” no título do tópico. Elas não somam em nada para o fórum, e não ajudam você a ser respondido mais rápido.

T

OK obrigado pelas informações.

T

Godoy contudo , contudo a minha principal duvida não foi sanada , o que eu gostaria de saber é como que insiro esse metodo no meu Jframe ? tenho um camo texto onde vou inserir o nome do cliente e um botão consultar onde quero que ele faça a ação de consultar em minha lista os dados dos clientes cadastrados e se eles não existirem retornar uma msg de erro.

ViniGodoy

Você insere no ConsultarActionPerformed.

Criado 20 de novembro de 2010
Ultima resposta 20 de nov. de 2010
Respostas 6
Participantes 3