Método de Pesquisa - ArrayList e Interface Java

Boa noite pessoal. Estou com um pequeno problema. Fiz um programa para administrar o sistema de uma locadora, onde é possível cadastrar, excluir e pesquisar o usuário/disco. O método de Cadastrar funciona tranquilamente, porém para pesquisar, estou tendo problemas. Seguem alguns trechos do código:

public class Principal {
public ArrayList <Usuario> usuarios = new ArrayList <Usuario>();
public ArrayList <Jogo> jogos = new ArrayList <Jogo>();
    
    public void cadastrarUsuario(int cod,String usuario,String nome,char tipo,char genero,String cpf,String senha){
        Usuario u = new Usuario();
        u.setCod(cod);
        u.setUsuario(usuario);
        u.setNome(nome);
        u.setTipo(tipo);
        u.setGenero(genero);
        u.setCpf(cpf);
        u.setSenha(senha);
        usuarios.add(u);
        }
    }

e

  public Usuario pesquisarUsuarioCod(int cod){
        Usuario u = new Usuario();
        for (int i=0;i<usuarios.size();i++){
            if(cod==usuarios.get(i).getCod()){
                u.setCod(cod);
                u.setNome(usuarios.get(i).getNome());
                u.setTipo(usuarios.get(i).getTipo());
                u.setGenero(usuarios.get(i).getGenero());
                u.setCpf(usuarios.get(i).getCpf());
                u.setSenha(usuarios.get(i).getSenha());
                return u;
            }
        }
        return null;
    }

O problema é que quando eu faço a pesquisa, depois de ter cadastrado algum objeto para testes, não consigo encontrá-lo.

Fiz um teste e cadastrei um objeto dentro do próprio método de pesquisar, algo como:

        public Usuario pesqList(ArrayList <Usuario> usuarios,String usuario){
        Usuario u = new Usuario();
        Usuario x = new Usuario(12,"A","dasdasd",'d','m',"31312","q3234");

Neste caso específico, é possível encontrar o objeto de código 12, porém ao cadastrar manualmente, não. Fiz uma série de outros testes e confirmei os seguintes fatos no meu código: o método de cadastrar está funcionando e armazena dados no arrayList, porém quando saímos do método cadastrar e no método pesquisar perguntamos pelo tamanho do ArrayList, ele aparece com tamanho 0.

Alguém tem ideia do que pode estar errado?

Promovi alguns ajuntes, entretanto, o foco é na realização das pesquisas.
Elas estão na classe principal, assim, o ideal é procurar compreender como cada pesquisa é realizada.
Ajuste a codificação da melhor forma que te atender.

Classe Principal com elementos de teste:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.swing.JOptionPane;

public class Principal {

    private final ArrayList<Usuario> usuarios = new ArrayList<>();
    private final ArrayList<Jogo> jogos = new ArrayList<>();

    public static void main(String[] args) {
        Principal teste = new Principal();
        
        teste.cadastrarUsuario(new Usuario("anaK100", "Ana Maria", fakeCpfOuSenha(true), fakeCpfOuSenha(false), (char) 1, 'F'));
        teste.cadastrarUsuario(new Usuario("Bilval", "Bia Larissa Vale", fakeCpfOuSenha(true), fakeCpfOuSenha(false), (char) 1, 'F'));
        teste.cadastrarUsuario(new Usuario("kanek", "Karol Nain Ekester", fakeCpfOuSenha(true), fakeCpfOuSenha(false), (char) 1, 'F'));
        teste.cadastrarUsuario(new Usuario("OOlOO", "Carlos Oliveira", fakeCpfOuSenha(true), fakeCpfOuSenha(false), (char) 1, 'M'));
        teste.cadastrarUsuario(new Usuario("CariAnaZOY", "Ana Maria", fakeCpfOuSenha(true), fakeCpfOuSenha(false), (char) 1, 'F'));
        try {
            teste.pesquisarUsuarioCod(2).ver();
            teste.pesquisarUsuarioCod(7).ver();
            teste.pesquisarUsuarioNome("ana maria", true).forEach(user -> user.ver());
            teste.pesquisarUsuarioNome("KANEK", false).forEach(user -> user.ver());
        } catch (NullPointerException e) {
            JOptionPane.showMessageDialog(null, "Uma pesquisa retornou NULL");
        } finally {
            teste.pesquisarUsuarioNome("ana maria", true).forEach(user -> user.ver());
            teste.pesquisarUsuarioNome("KANEK", false).forEach(user -> user.ver());
        }

    }

    //metodo de cadastramento de usuário estava longo demais
    private void cadastrarUsuario(Usuario user) {
        usuarios.add(user);
    }

    /*    as instruções que você criou são equivalentes à codificação abaixo, desde que
    todos os usuários tenham códigos de identificação diferentes.
        Recomendação: no lugar de um  ArrayList<Usuario>, dê preferência 
    a um HashSet<Usuario> e sobrescreva/implemente o equals e o HashSet na classe Usuario
     */
    private Usuario pesquisarUsuarioCod(int cod) {
        return usuarios.stream().filter(usuario -> usuario.getCod() == cod).findFirst().orElse(null);
    }

    /*diferente da pesquisa por cod, a pesquisa por nome deve retornar uma lista de usuários
    por isso alterei o tipo de retorno de Usuário para Lista de usuários
     */
    private List<Usuario> pesquisarUsuarioNome(String nome, boolean isPorNome) {
        return usuarios.stream().filter(usuario -> nome.equalsIgnoreCase(isPorNome ? usuario.getNome() : usuario.getNickName())).collect(Collectors.toList());
    }

    private static String fakeCpfOuSenha(boolean isCpf) {
        Random r = new Random();
        return IntStream.range(0, isCpf ? 11 : 8 + r.nextInt(12)).boxed().map(num -> r.nextInt(10)+"").reduce(String::concat).get();
    }
}

Classe usuário alterada e sem o construtor padrão:

class Usuario {

    //é melhor deixar que a classe incremente a codificação dos usuários
    private static int codificacao = 0;
    //depois de cadastrar, não será possível alterar a identidade/código do usuário por questões de integridade
    private final int cod;
    private String nickName, nome, cpf, senha;
    private char tipo, genero;

    public Usuario(String nickName, String nome, String cpf, String senha, char tipo, char genero) {
        this.cod = ++codificacao;
        this.nickName = nickName;
        this.nome = nome;
        this.cpf = cpf;
        this.senha = senha;
        this.tipo = tipo;
        this.genero = genero;
    }

    void setNickName(String nickName) {
        this.nickName = nickName;
    }

    void setNome(String nome) {
        this.nome = nome;
    }

    void setTipo(char tipo) {
        this.tipo = tipo;
    }

    void setGenero(char genero) {
        this.genero = genero;
    }

    void setCpf(String cpf) {
        this.cpf = cpf;
    }

    void setSenha(String senha) {
        this.senha = senha;
    }

    public int getCod() {
        return cod;
    }

    public String getNickName() {
        return nickName;
    }

    public String getNome() {
        return nome;
    }

    public String getCpf() {
        return cpf;
    }

    public String getSenha() {
        return senha;
    }

    public char getTipo() {
        return tipo;
    }

    public char getGenero() {
        return genero;
    }

    public static void ver(Usuario user) {
        System.out.println("Cod: " + user.cod + " nick: " + user.nickName + " nome: " + user.nome + " cpf: " + user.cpf + " senha: " + user.senha);
    }

    public void ver() {
        ver(this);
    }
}

Muito obrigado!! Fiz as implementações e o sistema me parece muito melhor agora. Porém, não sei fazer o cadastro do usuário na interface com o novo método, eu digo, com a classe principal sem o construtor. Antes eu estava fazendo assim:

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    boolean sts = false;
    int cod = 0;
    String usuario = null;
    String nome = null;
    String cpf = null;
    String senha = null;
    if(txtcCod.getText().equals("")){
        sts = true;
    }else{
        cod = Integer.parseInt(txtcCod.getText());
    }
    if(txtcUsuario.getText().equals("")){
        sts = true;
    }else{
        usuario = txtcUsuario.getText();
    }
    if(txtcNome.getText().equals("")){
        sts = true;
    }else{
        nome = txtcNome.getText();
    }
    if(txtcCpf.getText().equals("")){
        sts = true;
    }else{
        cpf = txtcCpf.getText();
    }
    if(txtcSenha.getText().equals("")){
        sts = true;
    }else{
        senha = txtcSenha.getText();
    }
    char tipo='n';
    char genero='n';

    if(cbbtipo.getSelectedIndex()==-1){
        sts = true;
    }else{
        if(cbbtipo.getSelectedIndex()==1){
            tipo='C';
        }
        if(cbbtipo.getSelectedIndex()==2){
            tipo='F';
        }
    }
    if(cbbgenero.getSelectedIndex()==-1){
        sts = true;
    }else{
        if(cbbgenero.getSelectedIndex()==1){
            tipo='M';
        }
        if(cbbtipo.getSelectedIndex()==2){
            tipo='F';
        }
    }
    int resposta;

    if(sts==true){
        resposta = JOptionPane.showConfirmDialog(null, "Há campos sem preencher! Deseja tentar novamente?");
        if (resposta == JOptionPane.YES_OPTION) {
            
        }else{
            this.dispose();
        }
    }else{
        p.cadastrarUsuario(cod,usuario,nome,tipo,genero,cpf,senha);
        JOptionPane.showMessageDialog(null, "Usuário Cadastrado!","Locadora das Galáxias | Sucesso", JOptionPane.INFORMATION_MESSAGE);
        this.dispose();
    }
}

Isso na minha tela “telapesquisausuario”. Estou tentando arrumar, mas desde já, muito obrigado, me ajudou muito!

Fiz os devidos ajustes para o cadastro. Mas agora, na tela pesquisa, preciso de um pouco de ajuda. Estava tentando fazer assim (apenas teste):

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    int cod = Integer.parseInt(codpesq.getText());
    int cod2 = p.pesquisarUsuarioCod(cod).getCod();
    JOptionPane.showMessageDialog(null, "cod2:"cod2,"Teste", JOptionPane.INFORMATION_MESSAGE);
}   

Porém não funcionou.

Você faz as verificações que tiver que fazer, depois de validar tudo, ai você realiza o cadastro de uma vez, ou seja, você não fica montando o usuário, você cadastra um completo, pois o construtor foi modificado justamente pensando nisto.

Implementação a seguir deve ser chamada dentro do método jButton1ActionPerformed:

private void cadastrar() {   
        //Arrays que serão usados para fins de validar o formulário de informar qual campo não foi preenchido
        String[] aviso = {"O Nick", "O nome", "O CPF", "A senha", "O tipo", "O sexo"};
        String[] dados = {txtcUsuario.getText(), txtcNome.getText(), txtcCpf.getText(), txtcSenha.getText(),
            cbbTipo.getSelectedIndex() > 0 ? "1" : "", cbbgenero.getSelectedIndex() > 0 ? "1" : ""};        
       
        //trecho que verifica a validade do fórmulário, se o resultado for -1 OK, se não aponta o campo a ser informado
        int cadastrar = IntStream.range(0, dados.length).filter(num -> dados[num].isEmpty()).findFirst().orElse(-1);
        if (cadastrar == -1) {
            char tipo = cbbTipo.getSelectedIndex() == 1 ? 'C' : 'F',
            genero = cbbgenero.getSelectedIndex() == 1 ? 'M' : 'F';
            //inserindo o usuário na lista de usuários cadsatrados
            cadastrarUsuario(new Usuario(txtcUsuario.getText(), txtcNome.getText(), txtcCpf.getText(), txtcSenha.getText(), tipo, genero));
            JOptionPane.showMessageDialog(null, "Usuário Cadastrado!", "Locadora das Galáxias | Sucesso", JOptionPane.INFORMATION_MESSAGE);

        } else {
            int resposta = JOptionPane.showConfirmDialog(this, aviso[cadastrar] + " do cliente não foi informado\nContinuar cadastrando? \n", "Cadatramento incompleto", JOptionPane.YES_NO_OPTION);
            if (resposta != JOptionPane.YES_OPTION) {
                this.dispose();
            }
        }
    }

Dê preferência a colocar um botão que permita voltar a tela inicial/sair, ao invés de fazer isso na validação do cadastro.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        Usuario user1 = pesquisarUsuarioCod(Integer.parseInt(codpesq.getText()));
        ArrayList<Usuario> listaDeUsuarios = pesquisarUsuario(txtcNome.getText());
        JOptionPane.showMessageDialog(null, "Usuario 1:" + user1.getCod() + " Usuários encontrados na lista: " + listaDeUsuarios.size());
    }

Renomei o nome das variáveis destes métodos jButton1ActionPerformed, para que possam fazer sentido.
Veja que os retornos importam, pois você queria pegar um código - int, mais o método de pesquisa retornava um usuário e é a partir dele(do objeto usuário retornado) que você acessa o código.
Lembre retornos importam.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Usuario user1 = pesquisarUsuarioCod(Integer.parseInt(codpesq.getText()));
    ArrayList<Usuario> listaDeUsuarios = pesquisarUsuario(txtcNome.getText());
    JOptionPane.showMessageDialog(null, "Usuario 1:" + user1.getCod() + " Usuários encontrados na lista: " + listaDeUsuarios.size());
}

Vou fazer a pesquisa, então obter o objeto desejado. Essa parte acho que entendi.

Agora vou precisar buscar do ArrayList na Classe principal para puxar os dados. como Nome, Usuário, CPF, etc? A minha intenção na tela pesquisar é: receber um código, pesquisar pelo usuário correspondente à esse código no ArrayList usuarios e então retornar os dados desse usuário.

Outro problema que eu acredito estar tendo, é que por alguma razão (talvez quando eu troque de JFrame) o ArrayList parece estar sendo zerado. Vou colar abaixo todas as classes de todos os pacotes. (Decidi não utilizar mais a senha):

Pacote Controller:
Classe Principal:

import java.util.ArrayList;
import model.Jogo;
import model.Usuario;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.swing.JOptionPane;
import view.telaprincipal;

public class Principal {
public ArrayList <Usuario> usuarios = new ArrayList <>();
public ArrayList <Jogo> jogos = new ArrayList <>();
    
public void cadastrarUsuario(Usuario user) {
    usuarios.add(user);
}
public Usuario pesquisarUsuarioCod(int cod) {
    System.out.println(usuarios.size());
    return usuarios.stream().filter(usuario -> usuario.getCod() == cod).findFirst().orElse(null);
}
public List<Usuario> pesquisarUsuarioNome(String nome, boolean isPorNome) {
    return usuarios.stream().filter(usuario -> nome.equalsIgnoreCase(isPorNome ? usuario.getNome() : usuario.getNickName())).collect(Collectors.toList());
}
public void cadastrarJogo(Jogo jogo) {
    jogos.add(jogo);
}
public Jogo pesquisarJogo(int cod){
        return jogos.stream().filter(jogo -> jogo.getCod() == cod).findFirst().orElse(null);
}
private static String fakeCpfOuSenha(boolean isCpf) {
    Random r = new Random();
    return IntStream.range(0, isCpf ? 11 : 8 + r.nextInt(12)).boxed().map(num -> r.nextInt(10)+"").reduce(String::concat).get();
}
    public static void main(String[] args) {
    Principal teste = new Principal();
    
    /*teste.cadastrarUsuario(new Usuario("anaK100", "Ana Maria", "teste", (char) 1, 'F'));
    teste.cadastrarUsuario(new Usuario("Bilval", "Bia Larissa Vale", "teste", (char) 1, 'F'));
    teste.cadastrarUsuario(new Usuario("kanek", "Karol Nain Ekester", "teste", (char) 1, 'F'));
    teste.cadastrarUsuario(new Usuario("OOlOO", "Carlos Oliveira", "teste", (char) 1, 'M'));
    teste.cadastrarUsuario(new Usuario("CariAnaZOY", "Ana Maria", "teste", (char) 1, 'F'));
    try {
        teste.pesquisarUsuarioCod(2).ver();
        teste.pesquisarUsuarioCod(7).ver();
        teste.pesquisarUsuarioNome("ana maria", true).forEach(user -> user.ver());
        teste.pesquisarUsuarioNome("KANEK", false).forEach(user -> user.ver());
    } catch (NullPointerException e) {
        JOptionPane.showMessageDialog(null, "Uma pesquisa retornou NULL");
    } finally {
        teste.pesquisarUsuarioNome("ana maria", true).forEach(user -> user.ver());
        teste.pesquisarUsuarioNome("KANEK", false).forEach(user -> user.ver());
    }*/
    telaprincipal tp = new telaprincipal();
    tp.setVisible(true);
}
    
}

Pacote Model

Classe Usuario:

private static int codificacao = 0;
//depois de cadastrar, não será possível alterar a identidade/código do usuário por questões de integridade
private final int cod;
private String nickName, nome, cpf, senha;
private char tipo, genero;

public Usuario(String nickName, String nome, String cpf, String senha, char tipo, char genero) {
    this.cod = ++codificacao;
    this.nickName = nickName;
    this.nome = nome;
    this.cpf = cpf;
    this.senha = senha;
    this.tipo = tipo;
    this.genero = genero;
}

void setNickName(String nickName) {
    this.nickName = nickName;
}

void setNome(String nome) {
    this.nome = nome;
}

void setTipo(char tipo) {
    this.tipo = tipo;
}

void setGenero(char genero) {
    this.genero = genero;
}

void setCpf(String cpf) {
    this.cpf = cpf;
}

void setSenha(String senha) {
    this.senha = senha;
}

public int getCod() {
    return cod;
}

public String getNickName() {
    return nickName;
}

public String getNome() {
    return nome;
}

public String getCpf() {
    return cpf;
}

public String getSenha() {
    return senha;
}

public char getTipo() {
    return tipo;
}

public char getGenero() {
    return genero;
}

public static void ver(Usuario user) {
    System.out.println("Cod: " + user.cod + " nick: " + user.nickName + " nome: " + user.nome + " cpf: " + user.cpf + " senha: " + user.senha);
}

public void ver() {
    ver(this);
}

}

Classe Jogo:

//ainda não mexi nessa classe

Pacote View:

telacadastrousuario: (não possui main pq é um jinternalframe e está num jframe com jdesktoppanel)

 package view;
import controller.Principal;
import java.util.stream.IntStream;
import javax.swing.JOptionPane;
import model.Usuario;
/*
 * @author Arthur Rezende
 */
public class telacadastrousuario extends javax.swing.JInternalFrame {
Principal p = new Principal();
/**
 * Creates new form telacadastrousuario
 */
public telacadastrousuario() {
    initComponents();
}

/**
 * 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();
    jPanel2 = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    txtcNome = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    cbbgenero = new javax.swing.JComboBox<>();
    jLabel6 = new javax.swing.JLabel();
    cbbtipo = new javax.swing.JComboBox<>();
    jButton1 = new javax.swing.JButton();
    jLabel8 = new javax.swing.JLabel();
    txtcUsuario = new javax.swing.JTextField();
    txtcCpf = new javax.swing.JTextField();

    setClosable(true);
    setTitle("Cadastro | Locadora das Galáxias");

    jLabel2.setText("Nome:");

    jLabel4.setText("CPF:");

    jLabel5.setText("Sexo:");

    cbbgenero.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Selecione", "Masculino", "Feminino" }));
    cbbgenero.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cbbgeneroActionPerformed(evt);
        }
    });

    jLabel6.setText("Tipo de Usuário:");

    cbbtipo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Selecione", "Cliente", "Funcionário" }));
    cbbtipo.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cbbtipoActionPerformed(evt);
        }
    });

    jButton1.setText("Cadastrar");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jLabel8.setText("Usuário:");

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

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(13, 13, 13)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addComponent(jLabel2)
                    .addGap(294, 294, 294)
                    .addComponent(jLabel5))
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addComponent(txtcNome, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(30, 30, 30)
                    .addComponent(cbbgenero, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addComponent(jLabel8)
                    .addGap(283, 283, 283)
                    .addComponent(jLabel6))
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addComponent(txtcCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(jLabel4)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addComponent(txtcUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(150, 150, 150)
                    .addComponent(cbbtipo, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(13, 13, 13))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(11, 11, 11)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel2)
                .addComponent(jLabel5))
            .addGap(4, 4, 4)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(txtcNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(cbbgenero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(14, 14, 14)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel8)
                .addComponent(jLabel6))
            .addGap(4, 4, 4)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(txtcUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(cbbtipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton1)
                .addComponent(txtcCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(23, 23, 23))
    );

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(10, 10, 10)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(6, 6, 6)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

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

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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    /*boolean sts = false;
    int cod = 0;
    String cpf = null;
    String usuario = null;
    String nome = null;
    if(txtcUsuario.getText().equals("")){
        sts = true;
    }else{
        usuario = txtcUsuario.getText();
    }
    if(txtcCpf.getText().equals("")){
        sts = true;
    }else{
        usuario = txtcUsuario.getText();
    }
    if(txtcNome.getText().equals("")){
        sts = true;
    }else{
        nome = txtcNome.getText();
    }
    if(txtcCpf.getText().equals("")){
        sts = true;
    }else{
        cpf = txtcCpf.getText();
    }
    char tipo='n';
    char genero='n';

    if(cbbtipo.getSelectedIndex()==-1){
        sts = true;
    }else{
        if(cbbtipo.getSelectedIndex()==1){
            tipo='C';
        }
        if(cbbtipo.getSelectedIndex()==2){
            tipo='F';
        }
    }
    if(cbbgenero.getSelectedIndex()==-1){
        sts = true;
    }else{
        if(cbbgenero.getSelectedIndex()==1){
            tipo='M';
        }
        if(cbbtipo.getSelectedIndex()==2){
            tipo='F';
        }
    }
    int resposta;

    if(sts==true){
        resposta = JOptionPane.showConfirmDialog(null, "Há campos sem preencher! Deseja tentar novamente?");
        if (resposta == JOptionPane.NO_OPTION) {
            this.setVisible(false);
        }
    }else{
        p.cadastrarUsuario(new Usuario(usuario,nome,cpf,tipo,genero));
        JOptionPane.showMessageDialog(null, "Usuário Cadastrado!","Locadora das Galáxias | Sucesso", JOptionPane.INFORMATION_MESSAGE);
        this.setVisible(false);;
        Principal teste = new Principal();
    }*/
    String[] aviso = {"O Nick", "O nome", "O CPF", "O tipo", "O sexo"};
    String[] dados = {txtcUsuario.getText(), txtcNome.getText(), txtcCpf.getText(),
        cbbtipo.getSelectedIndex() > 0 ? "1" : "", cbbgenero.getSelectedIndex() > 0 ? "1" : ""}; 
    int cadastrar = IntStream.range(0, dados.length).filter(num -> dados[num].isEmpty()).findFirst().orElse(-1);
    if (cadastrar == -1) {
        char tipo = cbbtipo.getSelectedIndex() == 1 ? 'C' : 'F',
        genero = cbbgenero.getSelectedIndex() == 1 ? 'M' : 'F';
        //inserindo o usuário na lista de usuários cadsatrados
        p.cadastrarUsuario(new Usuario(txtcUsuario.getText(), txtcNome.getText(), txtcCpf.getText(), tipo, genero));
        JOptionPane.showMessageDialog(null, "Usuário Cadastrado!", "Locadora das Galáxias | Sucesso", JOptionPane.INFORMATION_MESSAGE);

    } else {
        int resposta = JOptionPane.showConfirmDialog(this, aviso[cadastrar] + " do cliente não foi informado\nContinuar cadastrando? \n", "Cadatramento incompleto", JOptionPane.YES_NO_OPTION);
        if (resposta != JOptionPane.YES_OPTION) {
            this.dispose();
        }
    }
}                                        

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

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

}                                         


// Variables declaration - do not modify                     
private javax.swing.JComboBox<String> cbbgenero;
private javax.swing.JComboBox<String> cbbtipo;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField txtcCpf;
private javax.swing.JTextField txtcNome;
private javax.swing.JTextField txtcUsuario;
// End of variables declaration                   
}

telapesquisausuario:

 package view;

import controller.Principal;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import model.Usuario;

/*
 * @author Arthur Rezende
 */
public class telapesquisausuario extends javax.swing.JInternalFrame {
    Principal p = new Principal();
    /**
     * Creates new form telapesquisausuario
     */
    public telapesquisausuario() {
        initComponents();
    }

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

        jLabel12 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        codpesq = new javax.swing.JTextField();
        jPanel5 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lblnome = new javax.swing.JLabel();
        lblusuario = new javax.swing.JLabel();
        lblsexo = new javax.swing.JLabel();
        lbltipo = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        jLabel12.setText("jLabel12");

        setClosable(true);
        setTitle("Pesquisar Usuário | Locadora das Galáxias");

        jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Usuário"));
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Digite o Código do Usuário:");
        jPanel4.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(39, 49, -1, -1));
        jPanel4.add(codpesq, new org.netbeans.lib.awtextra.AbsoluteConstraints(208, 45, 100, -1));

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados:"));

        jLabel2.setText("Nome:");

        jLabel3.setText("Usuário:");

        jLabel5.setText("Sexo:");

        jLabel6.setText("Tipo:");

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(lblusuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6))
                        .addGap(33, 33, 33)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblsexo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lbltipo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(31, 31, 31)
                        .addComponent(lblnome, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(77, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(46, Short.MAX_VALUE)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(lblnome))
                .addGap(14, 14, 14)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(lblusuario))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(lblsexo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(lbltipo))
                .addGap(73, 73, 73))
        );

        jPanel4.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(25, 85, 454, 244));

        jButton1.setText("Pesquisar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel4.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(326, 41, -1, -1));

        jPanel3.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 6, 508, 355));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        Usuario user1 = p.pesquisarUsuarioCod(Integer.parseInt(codpesq.getText()));
        ArrayList<Usuario> listaDeUsuarios = new ArrayList<Usuario>();
        System.out.println(listaDeUsuarios.size());
        JOptionPane.showMessageDialog(null, "Usuario 1:" + user1.getCod() + " Usuários encontrados na lista: " + listaDeUsuarios.size());
    }                                        


    // Variables declaration - do not modify                     
    private javax.swing.JTextField codpesq;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JLabel lblnome;
    private javax.swing.JLabel lblsexo;
    private javax.swing.JLabel lbltipo;
    private javax.swing.JLabel lblusuario;
    // End of variables declaration                   
}

Desculpa se alterei alguma coisa que não devia, ainda sou iniciante em java e também em interface gráfica. Agradeço muito pela ajuda que tem me dado até agora.

Sim, a classe onde será realizada a pesquisa deve ter acesso a lista.

Os retornos possíveis são:
I - pesquisa por código retorna null, ou 1 usuário:
a) se null, contornar ou tratar o nullPointerException, pois ele já foi previsto na implementação;
b) se 1 usuário, pegar o que precisar dele (usuario.getAlgumaCoisa()).

II - Pesquisa por nome, retorna 1 lista, que pode conter 0 ou mais usuarios:
a) listaVazia = informar que a pesquisa não encontrou nada
b) lista contem algo, percorrer a lista e mostrar os usuários constantes na lista, escolher um e realizar uma ação: alterar, excluir, atualizar, consultar.
Por isso, o retorno importa, pois dois métodos que realizam pesquisa geram retornos diversos, cabendo prever o tipo de retorno e manipular a informação.
Assim, você consegue realizar encadeamentos como se estivesse lendo, ex.:

public static void main(String[] args) {
        contagem(1, 2, 3, 3, 4, 5, 5, 1).entrySet().forEach(item -> System.out.println(item.getKey() + " repetiu " + item.getValue() + " vez(es)"));
    }

private static Map<Double, Integer> contagem(double... valores) {
    Map<Double, Integer> contar = new TreeMap<>();        
    Arrays.stream(valores).forEach(valor -> contar.put(valor, contar.getOrDefault(valor, 0) + 1));
    return contar;
}

Esta instrução:
Arrays.stream(valores).forEach(valor -> contar.put(valor, contar.getOrDefault(valor, 0) + 1));

É equivalente a:

    for (int i = 0; i < valores.length; i++) {
        contar.putIfAbsent(valores[i], 0);
        contar.put(valores[i], contar.get(valores[i]) + 1);
    }

Excelente base: https://www.youtube.com/watch?v=NZDzuve7kho&list=PLxQNfKs8YwvGhXHbHtxtoB-tRRv6r3Rlr

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    Usuario user1 = p.pesquisarUsuarioCod(Integer.parseInt(codpesq.getText()));
    ArrayList<Usuario> listaDeUsuarios = (ArrayList<Usuario>) p.pesquisarUsuarioNome(nomepesq.getText(),true);
    JOptionPane.showMessageDialog(null, "Usuario 1:" + user1.getCod() + " Usuários encontrados na lista: " + listaDeUsuarios.size());
} 

Ele aponta erro nessa linha. Eu estou suspeitando que o Array, depois de cadastrar algum objeto, é apagado, ou algo assim, porque quando vou executar a pesquisa aparece sempre vazio.

Fluxo:
Tela de cadastro -> tela principal -> telaPesquisa.
Se o array esta na tela principal, você deve “emprestá-lo” a tela de cadastro.
Na tela de pesquisa ocorre a mesma coisa, você deve pegar o array emprestado da tela principal.
Todas as telas devem ter como atributo um
ArrayList <Usuario> usuarios = new ArrayList <>();
E ele vai transitar entres as telas de pesquisa e de cadastro por meio do construtor delas.
Ex.: adicione no construtor das classes cadastro e pesquisa o parametro
`ArrayList usuarios
Fica mais ou menos assim:

//para a tela de pesquisa

public ArrayList <Usuario> usuarios = new ArrayList <>();
public suaTelaPesquisa(o que ja tinha, ArrayList <Usuario> usuarios){
          o que ja tinha
          this.usuarios = usuarios;//transito concluído, pode pesquisar
}

//para a tela de cadastro

public ArrayList <Usuario> usuarios = new ArrayList <>();
public suaTelaCadastro(o que ja tinha, ArrayList <Usuario> usuarios){
          o que ja tinha
          this.usuarios = usuarios;//transito concluído, pode pesquisar
}

Tente, se não conseguir, poste a classe pesquisa sem o que estiver dentro do método initComponents(), pois aparentemente o erro deve estar no trânsito dos objetos por meio dos parâmetros dos construtores de cada classe.

O fluxo é assim: controller.Principal -> view.principal -> view.cadastro -> view.telaprincipal -> view.telapesquisa

Nessa linha:

 public static void main(String[] args) {
    Principal teste = new Principal();
    principal tp = new telaprincipal(usuarios); //NESSA LINHA
    tp.setVisible(true);

Aparece esse erro:
non static variable usuarios cannot be referenced from a static context

Fiz assim na classe controller.principal:

 public class Principal {
    public ArrayList <Usuario> usuarios = new ArrayList <>();
    public ArrayList <Jogo> jogos = new ArrayList <>();
        
        public static void main(String[] args) {
        Principal teste = new Principal();
        ArrayList <Usuario> usuarios = new ArrayList <>(); //declarei aqui denovo, ai sumiu o erro
        
        telaprincipal tp = new telaprincipal(usuarios);
        tp.setVisible(true);
    }
        
}

Em seguida na view.telaprincipal:

public class telaprincipal extends javax.swing.JFrame {
    public ArrayList <Usuario> usuarios = new ArrayList<>();
    
    public telaprincipal(ArrayList <Usuario> usuarios) {
        this.usuarios = usuarios;
        initComponents();
    }
}

Codificação apropriada:

public static void main(String[] args) {
        Principal teste = new Principal();       
        telaprincipal tp = new telaprincipal(teste.usuarios);//quem deve manipular a lista é o objeto criado
        tp.setVisible(true);
    }