Problemas com retorno de array

Olá galera do guj.

estou com alguns problemas aqui, não consigo retornar um array. segue o codigo:

public Cliente[] buscar(String buscaNome) throws Exception{
		
		Cliente[] clientes;
		
		ResultSet rs;
		
		PreparedStatement stmt = this.connection.prepareStatement("Select * from Cliente where nome=?");
		stmt.setString(1, buscaNome);
		
		rs = stmt.executeQuery();
		
		int cont = 0;
		while (rs.next()){
			Cliente aux = new Cliente();
			
			aux.setNome(rs.getString(1));
			aux.setRG(rs.getString(2));
			aux.setDataNascimento(rs.getString(3));
			aux.setSexo(rs.getString(4));
			
			
			clientes[cont] = aux;
			cont++;
		}
		
		stmt.close();
		
		return clientes;
	}

Como podem ver estou executando uma query e gostaria de retornar pelo metodo o reultado dessa query, desculpem a ignorancia, mas não consigo enchergar o problema.

Como posso resolver isso?

desde já obrigado

Robson sua consulta esta correta? você está procurando cliente com nome igual a ?
select *
from Cliente
where nome = ? -->> voce esta prcurando isso msm? se quiser todos os clientes coloca só

select *
from Cliente que ja vai dar certo, talvez o problema seja esse…

[quote=robsonperassoli]Olá galera do guj.

estou com alguns problemas aqui, não consigo retornar um array. segue o codigo:

Como podem ver estou executando uma query e gostaria de retornar pelo metodo o reultado dessa query, desculpem a ignorancia, mas não consigo enchergar o problema.

Como posso resolver isso?

desde já obrigado[/quote]

Pelo que entendi queres retornar um array de objetos!!
Já tentou trabalhar com ArrayList?

public ArrayList buscar(String buscaNome){
		
	 ArrayList<Cliente> lista = new ArrayList<Cliente>(); //Crio o objeto ArrayList do tipo Cliente
        Cliente aux = null;
			
		ResultSet rs;
		
 try{//prefira o try ao throws

		PreparedStatement stmt = this.connection.prepareStatement("Select * from Cliente where nome LIKE %?%");//Alterei um pouco o código aqui e procure sempre descrever os campos que vc quer
		stmt.setString(1, buscaNome);
		
		rs = stmt.executeQuery();
		
		while (rs.next()){
			aux = new Cliente();
			
			aux.setNome(rs.getString("nome"));//nomes dos campos das tabelas escritos
			aux.setRG(rs.getString("rg"));
			aux.setDataNascimento(rs.getString("dataNascimento"));
			aux.setSexo(rs.getString("sexo"));
			
			lista.add(aux); //Adiciono o objeto após o mesmo estar devidamente carregado não necessitando de contador
			
		}
	}
  	 catch(SQLException e){
  	   e.printStackTrace();
  	 }


		stmt.close();
		
		return lista;
	}

Bem o retorno vc trabalharia mais ou menos assim:

ClienteDAO  dao = new ClienteDAO();

ArrayList<Cliente> lista = new ArrayList<Cliente>();
lista = dao.buscar("Robson");
Cliente cliente = null;
int i;

for (i=0;i<lista.size();i++){
	cliente = (Cliente) lista.get(i);
			System.out.println(cliente getNome());  
			System.out.println(cliente .getRG());  
			System.out.println(cliente .getDataNascimento());  
			System.out.println(cliente .getSexo());  


					}

Lembrado que este ultimo é só um exemplo…

Qualquer coisa é só dar um grito

Um grande Abraço!>

O problema é que você não está instanciado o seu array. Falta algo do tipo:

   clientes = new Cliente[NUM_CLIENTES];

Pelo o que estou vendo aqui na api, não tem um método que te retorne o número de linhas do resultado (talvez eu simplesmente não tenha achado). De qualquer maneira, eu também aconselho a usar a interface List ou Collection, como o colega citou.

Ahh, começei a entender, na verdade o que mais se encaixa na minha situação é o exemplo do neoCortex com o arraylist, já que é uma consulta que pode retornar resultados em quantidades variadas, muito obrigado mesmo pela ajuda.

Robson, falta inicializar o array. Entretanto, por n motivos que tu podes encontrar facilmente nas buscas aqui no GUJ, é muito recomendável que utilizes ArrayList para guardar objetos.

Abraços

Olá, ainda estou com alguns problemas, realizo minha consulta tranquilo, porém não retorna nada nem dá nenhum tipo de erro. O que pode ser?

segue minha classe:

	public ArrayList buscar(String buscaNome){  
	     ArrayList<Cliente> lista = new ArrayList<Cliente>(); 
	     Cliente aux = null;  
	                
	     ResultSet rs;  
		              
	     try{
		   
		     PreparedStatement stmt = this.connection.prepareStatement("SELECT * FROM Cliente WHERE nome LIKE ?;");
		     stmt.setString(1,"'%"+buscaNome+"%'");  
		          
		     rs = stmt.executeQuery();  
		             
		     while (rs.next()){  
		         aux = new Cliente();  
		                 
		         aux.setNome(rs.getString(0));//nomes dos campos das tabelas escritos  
		         aux.setRG(rs.getString(1));  
		         aux.setDataNascimento(rs.getString(2));  
		         aux.setSexo(rs.getString(3));  
		                 
		         lista.add(aux);
		     } 
		     stmt.close();
		  }catch(SQLException e){  
		      e.printStackTrace();  
		  }   
		             
	      return lista;  
	} 

Na classe onde estou fazendo a consulta uso o seguinte codigo:

                if(evt.getSource() == this.btBuscar){
			try {
				ClienteDAO dao = new ClienteDAO();
				ArrayList clientes = new ArrayList();
				clientes = dao.buscar(this.tfBusca.getText());
				for(int i = 0; i<clientes.size();i++){
					Cliente cliente = (Cliente) clientes.get(i);
					this.lmClientes.add(0,cliente.getNome());
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

OBS: estou usando um JList para adicionar os objetos retornados pelo arrayList;

repito, não acontece erro algum, nem na compilação nem na consulta no banco…
Se puderem me dar uma mãozinha… :smiley:
Obrigado.>

Posso sugerir uma mudança? Use o enhanced-for e os tipos específicos na lista (a partir do Java 1.5):

ClienteDAO dao = new ClienteDAO();
List<Cliente> clientes = new ArrayList<Cliente>();
clientes = dao.buscar(this.tfBusca.getText()).
for (Cliente cliente : clientes) {
    this.lmClientes.add(0, cliente.getNome());
}

Uma pergunta: o objeto lmClientes é de que tipo?

[quote=marcobiscaro2112]Posso sugerir uma mudança? Use o enhanced-for e os tipos específicos na lista (a partir do Java 1.5):

ClienteDAO dao = new ClienteDAO();
List<Cliente> clientes = new ArrayList<Cliente>();
clientes = dao.buscar(this.tfBusca.getText()).
for (Cliente cliente : clientes) {
    this.lmClientes.add(0, cliente.getNome());
}

Uma pergunta: o objeto lmClientes é de que tipo?[/quote]

lmClientes é o ListModel, usado para adicionar os componentes na JList;

não conhecia o enhanced-for, sou novato mesmoo…

obrigado pela dica, porém como posso resolver o meu problema com a consulta?

É um DefaultListModel? Eu nunca usei um, mas segundo a documentação:

O primeiro argumento é o índice no qual se insere o valor. Mas é sempre zero?
Será esse o problema? Talvez esteja falando besteira… mas verifique isso.

[quote=marcobiscaro2112]É um DefaultListModel? Eu nunca usei um, mas segundo a documentação:

O primeiro argumento é o índice no qual se insere o valor. Mas é sempre zero?
Será esse o problema? Talvez esteja falando besteira… mas verifique isso.[/quote]

Sim, é um DefaultListmodel.
na verdade o 0 é para adicionar na primeira posição da lista, já tentei mudai isso tbm.

Creio que o erro seja na consulta, pois quando tento inserir no banco de dados acontece a mesma coisa, nada adicionado e nenhum erro nem no banco nem na compilação do programa.

segue o código para inserção de dados, caso queira dar uma olhada.


public void adiciona(Cliente cliente){
		try{
		    PreparedStatement stmt = 
	 		this.connection.prepareStatement("INSERT INTO cliente VALUES (?,?,?,?)"); 
		    stmt.setString(1, cliente.getNome());
		    stmt.setString(2, cliente.getRG());
		    stmt.setString(3, cliente.getDataNascimento());
		    stmt.setString(4, cliente.getSexo());
		
		    javax.swing.JOptionPane.showMessageDialog(null,stmt);
		
		    stmt.execute();
		    stmt.close();
		    
		}catch(Exception e){
			e.getStackTrace();
		}
	}

estou usando o postgresql como banco. Não sei usá-lo muito bem também.

O JOptionPane.showMessegeDialog funciona (aparece a janela), ou nem isso?

Talvez tenha encontrado um possível problema:

if(evt.getSource() == this.btBuscar){
    try {
	ClienteDAO dao = new ClienteDAO();
        List<Cliente> clientes = new ArrayList<Cliente>();
        clientes = dao.buscar(this.tfBusca.getText()).
        for (Cliente cliente : clientes) {
            this.lmClientes.add(0, cliente.getNome());
            // aqui você adiciona o dado no modelo, certo
            // mas quando é que você adiciona o modelo na JList?
        }
        // será que não falta isso:
        this.jList.setModel(this.lmClientes);
    } catch (Exception e) {
	e.printStackTrace();
    }
}

Tente isso.

Eu já adicionei o list model, continua o mesmo erro, tentei também aquele showmessagedialog, funcionou, e mostrou a query certa, como deve ser.

não entendo o que pode ser, talvez não é alguma configuração do banco?

estou me descabelando aqui. Não entendo o que pode ser. Tentei tudo o que conheco para tentar resolver, pesquisei muito, e nada. Uma luz por favor.

Cara, posta todo o seu código fonte aqui (do DAO, do Cliente e do formulário). Vamos resolver!

Aqui estão os codigos:

Cliente.java

public class Cliente {
	
	public Cliente(){
		
	}
	
	
	
	public void setNome(String nome){
		this.nome = nome;
	}
	public String getNome(){
		return this.nome;
	}
	
	
	
	public void setRG(String rg){
		this.rg = rg;
	}
	public String getRG(){
		return this.rg;
	}
	
	
	
	public void setDataNascimento(String dataNascimento){
		this.dataNascimento = dataNascimento;
	}
	public String getDataNascimento(){
		return this.dataNascimento;
	
	}
	
	
	public void setSexo(String sexo){
		this.sexo = sexo;
	}
	public String getSexo(){
		return this.sexo;
	}
	
	
	
	private String nome;
	private String rg;
	private String dataNascimento;
	private String sexo;
	

}

ClienteDAO.java

import java.sql.*;
import java.util.ArrayList;


public class ClienteDAO {
	
	private Connection connection;
	
	public ClienteDAO(){
		try{
		this.connection = ConnectionFactory.getConnection();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	public void adiciona(Cliente cliente){
		try{
		    PreparedStatement stmt = 
	 		this.connection.prepareStatement("INSERT INTO cliente VALUES (?,?,?,?)"); 
		    stmt.setString(1, cliente.getNome());
		    stmt.setString(2, cliente.getRG());
		    stmt.setString(3, cliente.getDataNascimento());
		    stmt.setString(4, cliente.getSexo());
		
		    javax.swing.JOptionPane.showMessageDialog(null,stmt);
		
		    stmt.execute();
		    stmt.close();
		    
		}catch(Exception e){
			e.getStackTrace();
		}
	}
	
	public void deleta(Cliente cliente) throws Exception{
		PreparedStatement stmt = this.connection.prepareStatement("delete from Cliente where nome=?");
		stmt.setString(1, cliente.getNome());
		
		stmt.execute();
		stmt.close(); 
	}
	
	public ArrayList buscar(String buscaNome){  
	     ArrayList<Cliente> lista = new ArrayList<Cliente>(); 
	     Cliente aux = null;  
	                
	     ResultSet rs;  
		              
	     try{
		   
		     PreparedStatement stmt = this.connection.prepareStatement("SELECT * FROM Cliente WHERE nome LIKE ?;");
		     stmt.setString(1,"'%"+buscaNome+"%'");  
		          
		     rs = stmt.executeQuery();  
		             
		     while (rs.next()){  
		         aux = new Cliente();  
		                 
		         aux.setNome(rs.getString(0));//nomes dos campos das tabelas escritos  
		         aux.setRG(rs.getString(1));  
		         aux.setDataNascimento(rs.getString(2));  
		         aux.setSexo(rs.getString(3));  
		                 
		         lista.add(aux);
		     } 
		     stmt.close();
		  }catch(SQLException e){  
		      e.printStackTrace();  
		  }   
		             
	      return lista;  
	}  

}

FmClientes.java

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;


public class FmClientes implements ActionListener{
	
	 private JFrame janelaClientes = new JFrame("Clientes");
	 private JButton btNovo = new JButton("Novo");
	 private JButton btExcluir = new JButton("Excluir");
	 
	 private JMenuBar mnPrincipal = new JMenuBar();
	 private JMenu mnArquivo = new JMenu("Arquivo");
	 private JMenuItem itNovo = new JMenuItem("Novo");
	 private JMenuItem itExcluir = new JMenuItem("Excluir");
	 private JMenuItem itSair = new JMenuItem("Sair");
	 
	 
	public FmClientes(){
		this.janelaClientes.setVisible(true);
		this.janelaClientes.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.janelaClientes.setResizable(false);
		this.janelaClientes.setLayout(new GridLayout(1,2));
		
		this.janelaClientes.setJMenuBar(this.mnPrincipal);
		this.mnPrincipal.add(this.mnArquivo);
		this.mnArquivo.add(this.itNovo);
		this.mnArquivo.add(this.itExcluir);
		this.mnArquivo.add(this.itSair);
		
		this.btNovo.addActionListener(this);
		this.itNovo.addActionListener(this);
		this.btExcluir.addActionListener(this);
		this.itExcluir.addActionListener(this);
		this.itSair.addActionListener(this);
		
		this.janelaClientes.add(this.btNovo);
		this.janelaClientes.add(this.btExcluir);
		
        this.janelaClientes.pack();
	}

	public static void main(String[] args) {
		new FmClientes();
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		
		if (evt.getSource() == this.itNovo || evt.getSource() == this.btNovo){
			new FmInserirCadastro();
		}else if(evt.getSource() == this.itExcluir || evt.getSource() == this.btExcluir){
			new FmExcluirCadastro();			
		}else if(evt.getSource() == itSair){
			System.exit(0);
		}
		
	}

}

FmExcluirCadastro.java


import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class FmExcluirCadastro implements ActionListener{

	private JFrame janela = new JFrame("Excluir Cadastro");
	private JPanel pnBusca = new JPanel();
	private JPanel pnResult = new JPanel();
	
	private JLabel lbBuscar = new JLabel("Buscar: ");
	private JTextField tfBusca = new JTextField();
	private JButton btBuscar = new JButton("Ir");
	private JButton btExcluir = new JButton("Excluir");
	
	private JList ltClientes = new JList();
	private DefaultListModel lmClientes = new DefaultListModel();
	
	
	
	
	public FmExcluirCadastro(){
		this.janela.setVisible(true);
		this.janela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.janela.setResizable(false);
		this.janela.setLayout(new GridLayout(1,2));
		
		this.tfBusca.setText("    ");
		this.btBuscar.addActionListener(this);
		
		this.pnBusca.add(this.lbBuscar);
		this.pnBusca.add(this.tfBusca);
		this.pnBusca.add(this.btBuscar);
		
		this.pnResult.setLayout(new GridLayout(2,2));
		this.pnResult.add(this.ltClientes);
		this.pnResult.add(this.btExcluir);		
		
		this.janela.add(this.pnBusca);
		this.janela.add(this.pnResult);
		
		this.lmClientes.add(0,"Clientes:");
		this.ltClientes.setModel(this.lmClientes);
		
		
		this.janela.pack();
	}
	
	
	public static void main(String[] args) {
		new FmExcluirCadastro();
	}


	@Override
	public void actionPerformed(ActionEvent evt) {
		if(evt.getSource() == this.btBuscar){
			try {
				ClienteDAO dao = new ClienteDAO();
				ArrayList<Cliente> clientes = new ArrayList<Cliente>(); 
				clientes = dao.buscar(this.tfBusca.getText());
				for (Cliente cliente : clientes) {  
					this.lmClientes.add(0,cliente.getNome());
				} 
				this.ltClientes.setModel(this.lmClientes);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

}

FmInserirCadastro.java


import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;


public class FmInserirCadastro implements ActionListener{

	private JFrame janela = new JFrame("Inserir Cadastro");
	
	private JMenuBar menuBar =new JMenuBar();
	private JMenu Principal = new JMenu("Principal");
	private JMenuItem sair = new JMenuItem("Sair");
	
	private JTextField tfNome = new JTextField();
	private JTextField tfRg = new JTextField();
	private JTextField tfNascimento = new JTextField();
	private JComboBox cbSexo = new JComboBox();
	private JButton btSalvar = new JButton("Salvar");
	
	private JLabel lbNome = new JLabel("Nome: ");
	private JLabel lbRg = new JLabel("RG: ");
	private JLabel lbSexo = new JLabel("Sexo: ");
	private JLabel lbNascimento = new JLabel("Data de Nascimento: ");
	
	private Cliente novoCliente = new Cliente();


	//construtor
	public FmInserirCadastro(){
		janela.setVisible(true);
		janela.setDefaultCloseOperation(janela.DISPOSE_ON_CLOSE);
		janela.setResizable(false);
		
		this.Principal.add(this.sair);
		this.menuBar.add(this.Principal);
		janela.setJMenuBar(this.menuBar);
		
		janela.setLayout(new GridLayout(5,2));
		
		janela.add(this.lbNome);
		janela.add(this.tfNome);
		janela.add(this.lbRg);
		janela.add(this.tfRg);
		janela.add(this.lbSexo);
		janela.add(this.cbSexo);
		this.cbSexo.addItem("Masculino");
		this.cbSexo.addItem("Feminino");
		janela.add(this.lbNascimento);
		janela.add(this.tfNascimento);
		janela.add(this.btSalvar);
		
		this.btSalvar.addActionListener(this);
		this.sair.addActionListener(this);
		
		janela.pack();
	}
	
	
	public static void main(String[] args) {
		new FmInserirCadastro();
	}



	@Override
	public void actionPerformed(ActionEvent evt) {
		
		if (evt.getSource() == this.btSalvar){
			
			
			//////verificar
			if(!this.tfNome.getText().equals("") && !this.tfNascimento.getText().equals("") &&
				!this.tfRg.getText().equals("")){
				
				
				this.novoCliente.setNome(this.tfNome.getText());
				this.novoCliente.setRG(this.tfRg.getText());				
				this.novoCliente.setDataNascimento(this.tfNascimento.getText());
				String sexo = (String)this.cbSexo.getSelectedItem();				
				this.novoCliente.setSexo(sexo);
				
				try{
				  ClienteDAO dao = new ClienteDAO();
				  dao.adiciona(novoCliente);
				}catch(Exception e){
					javax.swing.JOptionPane.showMessageDialog(null, "Erro ao inserir no banco de dados");
				}
				
				
			}else{
				javax.swing.JOptionPane.showMessageDialog(null,"Todos os campos devem ser preenchidos!");
			}
			
		}else if(evt.getSource() == this.sair){
			this.janela.dispose();			
		}
		
	}

}

ConectionFactory.java

import java.sql.*;

public class ConnectionFactory {
	
  public static Connection getConnection() throws Exception{ 
	    
    try {
      Class.forName ("org.postgresql.Driver").newInstance();
      return DriverManager.getConnection("jdbc:postgresql://localhost:5432/java_clientes","java", "java");
    } catch (ClassNotFoundException e) {
      throw new SQLException(e.getMessage());
    }
  }
  
}

Em ClientesDAO, na linha 45, mude a assinatura do método para:

public ArrayList<Cliente> buscar(String buscaNome) {

Na linha 54 não entendi o porque dos “%”…

Os “%” são usados na consulta sql para pegar qualquer string que contenha o que está entre os “%”

Ahh… essa eu não sabia.

Calma que eu estou analisando (passei tudo para o Eclipse e fiz uma adaptação para MySQL). Estou fazendo testes…

Meu caro, como você pode ver as janelas estão um tanto quanto feias. Como poderia fazer para melhorar o layout? :oops: :oops:

Boas notícias!!!
Veja algumas alterações:
ClientesDAO.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class ClienteDAO {

	private Connection connection;

	public ClienteDAO() {
		try {
			this.connection = ConnectionFactory.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void adiciona(Cliente cliente) {
		try {
			PreparedStatement stmt = this.connection
			.prepareStatement("INSERT INTO cliente VALUES (?,?,?,?)");
			stmt.setString(1, cliente.getNome());
			stmt.setString(2, cliente.getRG());
			stmt.setString(3, cliente.getDataNascimento());
			stmt.setString(4, cliente.getSexo());

			javax.swing.JOptionPane.showMessageDialog(null, stmt);

			stmt.execute();
			stmt.close();

		} catch (Exception e) {
			e.getStackTrace();
		}
	}

	public void deleta(Cliente cliente) throws Exception {
		PreparedStatement stmt = this.connection
		.prepareStatement("delete from Cliente where nome=?");
		stmt.setString(1, cliente.getNome());

		stmt.execute();
		stmt.close();
	}

	// modificado!!
	// use o tipo específico
	public ArrayList<Cliente> buscar(String buscaNome) {
		ArrayList<Cliente> lista = new ArrayList<Cliente>();
		Cliente aux = null;

		ResultSet rs;

		try {

			PreparedStatement stmt = this.connection
			.prepareStatement("SELECT * FROM Cliente WHERE nome LIKE ?;");
			stmt.setString(1, "%" + buscaNome + "%");

			System.out.println(stmt.toString());
			rs = stmt.executeQuery();

			while (rs.next()) {
				aux = new Cliente();
				// modificado!
				// o índice começa do 1 (pelo menos no MySQL)
				aux.setNome(rs.getString(1));
				aux.setRG(rs.getString(2));
				aux.setDataNascimento(rs.getString(3));
				aux.setSexo(rs.getString(4));

				lista.add(aux);
			}
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return lista;
	}

}

FmExcluirCadastro.java

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FmExcluirCadastro implements ActionListener {

	private JFrame janela = new JFrame("Excluir Cadastro");
	private JPanel pnBusca = new JPanel();
	private JPanel pnResult = new JPanel();

	private JLabel lbBuscar = new JLabel("Buscar: ");
	private JTextField tfBusca = new JTextField(5); // modificado!
	// ao invés de colocar espaços vazios, use isso para definir o tamanho
	private JButton btBuscar = new JButton("Ir");
	private JButton btExcluir = new JButton("Excluir");

	private JList ltClientes = new JList();
	private DefaultListModel lmClientes = new DefaultListModel();

	public FmExcluirCadastro() {
		this.janela.setVisible(true);
		this.janela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.janela.setResizable(false);
		this.janela.setLayout(new GridLayout(1, 2));

		// this.tfBusca.setText("");
		// modificado!
		// vide anotação acima
		this.btBuscar.addActionListener(this);

		this.pnBusca.add(this.lbBuscar);
		this.pnBusca.add(this.tfBusca);
		this.pnBusca.add(this.btBuscar);

		this.pnResult.setLayout(new GridLayout(2, 2));
		this.pnResult.add(this.ltClientes);
		this.pnResult.add(this.btExcluir);

		this.janela.add(this.pnBusca);
		this.janela.add(this.pnResult);

		this.lmClientes.add(0, "Clientes:");
		this.ltClientes.setModel(this.lmClientes);

		this.janela.setSize(200, 200);
		// this.janela.pack();
		// modificado!
		// mudei o tamanho para aparecer a JList inteira
	}

	public static void main(String[] args) {
		new FmExcluirCadastro();
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		if (evt.getSource() == this.btBuscar) {
			try {
				ClienteDAO dao = new ClienteDAO();
				ArrayList<Cliente> clientes = new ArrayList<Cliente>();
				clientes = dao.buscar(this.tfBusca.getText());
				for (Cliente cliente : clientes) {
					this.lmClientes.add(1, cliente.getNome()); //modificado!
					// adicionar a partir do 1 para o título ficar na posição zero
				}
				this.ltClientes.setModel(this.lmClientes);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}

FmInserirCadastro.java

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;

public class FmInserirCadastro implements ActionListener {

	private JFrame janela = new JFrame("Inserir Cadastro");

	private JMenuBar menuBar = new JMenuBar();
	private JMenu Principal = new JMenu("Principal");
	private JMenuItem sair = new JMenuItem("Sair");

	private JTextField tfNome = new JTextField();
	private JTextField tfRg = new JTextField();
	private JTextField tfNascimento = new JTextField();
	private JComboBox cbSexo = new JComboBox();
	private JButton btSalvar = new JButton("Salvar");

	private JLabel lbNome = new JLabel("Nome: ");
	private JLabel lbRg = new JLabel("RG: ");
	private JLabel lbSexo = new JLabel("Sexo: ");
	private JLabel lbNascimento = new JLabel("Data de Nascimento: ");

	private Cliente novoCliente = new Cliente();

	// construtor
	public FmInserirCadastro() {
		janela.setVisible(true);
		janela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // modificado!
		// o método é estático, logo refencie a classe e não o objeto
		janela.setResizable(false);

		this.Principal.add(this.sair);
		this.menuBar.add(this.Principal);
		janela.setJMenuBar(this.menuBar);

		janela.setLayout(new GridLayout(5, 2));

		janela.add(this.lbNome);
		janela.add(this.tfNome);
		janela.add(this.lbRg);
		janela.add(this.tfRg);
		janela.add(this.lbSexo);
		janela.add(this.cbSexo);
		this.cbSexo.addItem("Masculino");
		this.cbSexo.addItem("Feminino");
		janela.add(this.lbNascimento);
		janela.add(this.tfNascimento);
		janela.add(this.btSalvar);

		this.btSalvar.addActionListener(this);
		this.sair.addActionListener(this);

		janela.pack();
	}

	public static void main(String[] args) {
		new FmInserirCadastro();
	}

	@Override
	public void actionPerformed(ActionEvent evt) {

		if (evt.getSource() == this.btSalvar) {

			// ////verificar
			if (!this.tfNome.getText().equals("")
					&& !this.tfNascimento.getText().equals("")
					&& !this.tfRg.getText().equals("")) {

				this.novoCliente.setNome(this.tfNome.getText());
				this.novoCliente.setRG(this.tfRg.getText());
				this.novoCliente.setDataNascimento(this.tfNascimento.getText());
				String sexo = (String) this.cbSexo.getSelectedItem();
				this.novoCliente.setSexo(sexo);

				try {
					ClienteDAO dao = new ClienteDAO();
					dao.adiciona(novoCliente);
				} catch (Exception e) {
					javax.swing.JOptionPane.showMessageDialog(null,
					"Erro ao inserir no banco de dados");
				}

			} else {
				javax.swing.JOptionPane.showMessageDialog(null,
				"Todos os campos devem ser preenchidos!");
			}

		} else if (evt.getSource() == this.sair) {
			this.janela.dispose();
		}

	}

}