Trabalho da Facu em java usando Jframe

3 respostas
txtprogramaçãojavajframe
M

Pessoal estou desenvolvendo um trabalho da faculdade que precisa ter: Cadastro de usuário(salvo em txt), e busca por id. Fiz o codigo de busca porém não estou conseguindo colocar no jframe , para o usuario digitar o id e aparecer a linha do cadastro.!

Código fonte:

public class FuncPesquisa {

//int IdPesquisa = 0;
public static String IdPesquisa = null;
public String Pesquisar() throws FileNotFoundException{
    
    File arquivo = new File("C:\\Users\\MVPI\\Desktop\\TrabalhoPersist\\Cadastro.txt");
    try{
    FileReader FR = new FileReader (arquivo);
        BufferedReader br = new BufferedReader(FR);
        while (br.ready()){
            String linha = br.readLine();
           if( linha == null){
               break;
           }
           if(linha.matches(IdPesquisa)){
               return linha;
               
           }
          // System.out.println(""+linha);
               
           }
            
            //System.out.println(""+IdPesquisa); teste para ver se estava funcionando so que não printou nada no console
        
    }catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return "id não encontrado";
}
        
      
}

Código fonte Jframe Pesquisar:

public class Pesquisa extends javax.swing.JFrame {

public Pesquisa() {
    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() {

    Voltar = new javax.swing.JButton();
    BotaoPesquisa = new javax.swing.JButton();
    jPesquisa = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    Voltar.setFont(new java.awt.Font("Comic Sans MS", 3, 14)); // NOI18N
    Voltar.setText("Voltar");
    Voltar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            VoltarActionPerformed(evt);
        }
    });

    BotaoPesquisa.setFont(new java.awt.Font("Comic Sans MS", 3, 14)); // NOI18N
    BotaoPesquisa.setText("Pesquisar");
    BotaoPesquisa.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            BotaoPesquisaActionPerformed(evt);
        }
    });

    jPesquisa.setFont(new java.awt.Font("Comic Sans MS", 3, 14)); // NOI18N
    jPesquisa.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jPesquisaActionPerformed(evt);
        }
    });

    jLabel1.setFont(new java.awt.Font("Comic Sans MS", 3, 14)); // NOI18N
    jLabel1.setText("ID :");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(Voltar))
                .addGroup(layout.createSequentialGroup()
                    .addGap(88, 88, 88)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(BotaoPesquisa))
                    .addGap(0, 75, Short.MAX_VALUE)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(Voltar, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(BotaoPesquisa)
                    .addGap(0, 252, Short.MAX_VALUE)))
            .addContainerGap())
    );

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

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

private void jPesquisaActionPerformed(java.awt.event.ActionEvent evt) {                                          
    
    //Campo para o usuario digitar o id
     FuncPesquisa.IdPesquisa = jPesquisa.getText();
    
    
           
           
    
    
}                                         

private void BotaoPesquisaActionPerformed(java.awt.event.ActionEvent evt) {                                              
    FuncPesquisa Buscar = new FuncPesquisa();
    FuncPesquisa.IdPesquisa = jPesquisa.getText();
    
    //botão de pesquisar
            JOptionPane.showMessageDialog(null, Buscar);
}                                             

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

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            
            
            new Pesquisa().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton BotaoPesquisa;
private javax.swing.JButton Voltar;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jPesquisa;
// End of variables declaration

}

3 Respostas

J

Bom, você pode importar a classe FuncPesquisa para a classe onde está JFrame, caso esteja em um pacote diferente. Depois, basta instanciar a classe FuncPesquisa e usá-la, como, por exemplo, algo do tipo (um exemplo despretensioso):

private void pesquisarDados(){
    	FuncPesquisar funcaoPesquisa = new FuncPesquisar();
    	funcaoPesquisa.setIdPesquisa( jTextField.getText().trim());
    	jTextArea.setText(funcaoPesquisa.pesquisar());
    }

Obs 1: por convenção, os nomes de métodos são escritos com letra minúscula. Logo, troquei Pesquisar por pesquisar.

Obs 2: por convenção, os nomes de variáveis são escritos com letra minúscula. Logo, troquei IdPesquisa por idPesquisa.

Obs 3: é melhor encapsular a variável idPesquisa (tornando-a privada e usando os métodos acessores e modificadores para manipulá-la - setters e getters). Logo, fiz:

funcaoPesquisa.setIdPesquisa( jTextField.getText().trim());

e não

funcaoPesquisa.idPesquisa = jTextField.getText().trim();

M

Opa blz valeu pelo comentário, agora conseguir executar a função, joguei o que tinha feito dentro do Jframe, consegui rodar so que não consigo comparar o Id que o usuário digita com o do cadastro, para mostrar so a linha que esta com id. Porém com esse código ele mostra todos os cadastro existente dentro txt. Queria saber como faço para comparar a Id digitada com a Id do cadastro e mostrar so a linha de ID.

File txt = new File("C:\\Users\\MVPI\\Desktop\\TrabalhoPersist\\Cadastro.txt");
           try{
               String Numepesquisa = (jPesquisa.getText());
               FileReader FR = new FileReader (txt);
                BufferedReader br = new BufferedReader(FR);
                  while (br.ready()){
                  String linha = br.readLine();
                         if( linha == null){
                          JOptionPane.showMessageDialog(null, "Cadastro não encontrado");
                          
                            } 
                            else{

                             JOptionPane.showMessageDialog(null, linha);
                            }
           
               
                    }
             }catch (FileNotFoundException e) {
		
                     e.printStackTrace();
                    
                } catch (IOException ex) {
                
                        
		ex.printStackTrace();
                }
J

Se você consultar a documentação (BufferedReader - readLine()), verás que:

Reads a line of text. A line is considered to be terminated by any one of a line feed (’\n’), a carriage return (’\r’), a carriage return followed immediately by a line feed, or by reaching the end-of-file (EOF).

“Lê uma linha de texto. Uma linha é considerada terminada quando for encontrado qualquer avanço de linha, ou seja, um ‘\n’, um retorno de carro ‘\r’, um retorno de carro seguido imediatamente ou um avanço de linha ‘\n’, ou ao atingir uma final de arquivo (EOF - End of File)”.

Logo, se o métodoreadLine() está lendo a todo o arquivo, então nenhum desses ‘terminadores’ foi encontrado no arquivo, exceto o EOF.
Como está o layout do arquivo txt?

Criado 24 de setembro de 2019
Ultima resposta 25 de set. de 2019
Respostas 3
Participantes 2