Vetor para utilizar em interface gráfica Swing

Bom dia,

criei um programa para que seja cadastrado livros contendo nome, autor e resumo. É criada uma interface gráfica através do swing e os livros cadastrados são armazenados em um arquivo.txt.

Gostaria de implementar uma pesquisa nos livros cadastrados e para isso pensei em armazenar as informações dos livros em um vetor (mantendo o arquivo.txt). Só não sei como faço isso, pois eu teria que criar um vetor do tipo Livro, mas e como farei a estrutura para que sejam armazenadas os de nome, autor e resumo na posição i.

public class Livro {
    
    public String nome;
    public String autor;
    public String resumo;
}


public class CadastroAndPesquisa extends javax.swing.JFrame {

        /**
         * Creates new form Cadastro
         */
        public CadastroAndPesquisa() {
            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();
            lb2 = new javax.swing.JLabel();
            lb3 = new javax.swing.JLabel();
            lb4 = new javax.swing.JLabel();
            txt1 = new javax.swing.JTextField();
            txt2 = new javax.swing.JTextField();
            txt3 = new javax.swing.JTextField();
            btn1 = new javax.swing.JButton();
            lb1 = new javax.swing.JLabel();
            btn2 = new javax.swing.JButton();
            lb5 = new javax.swing.JLabel();
            lb6 = new javax.swing.JLabel();
            txt4 = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            lb2.setText("Título:");

            lb3.setText("Autor:");

            lb4.setText("Resumo:");

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

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

            btn1.setText("Cadastra");
            btn1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btn1ActionPerformed(evt);
                }
            });

            lb1.setText("Cadastro de Livros");

            btn2.setText("Pesquisar");

            lb5.setText("Pesquisa de Livros");

            lb6.setText("Título:");

            jLabel1.setText("====================================================");

            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGap(149, 149, 149)
                                    .addComponent(lb1))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGap(157, 157, 157)
                                    .addComponent(lb5)))
                            .addGap(0, 0, Short.MAX_VALUE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(lb2)
                                    .addGap(5, 5, 5)
                                    .addComponent(txt1))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(lb3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(txt2))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                    .addGap(0, 0, Short.MAX_VALUE)
                                    .addComponent(lb4)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(btn1)
                                        .addComponent(txt3, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(lb6)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(txt4)))))
                    .addContainerGap())
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(157, 157, 157)
                    .addComponent(btn2)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(lb1)
                    .addGap(5, 5, 5)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lb2)
                        .addComponent(txt1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lb3)
                        .addComponent(txt2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(txt3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btn1))
                        .addComponent(lb4))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(lb5)
                    .addGap(2, 2, 2)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lb6)
                        .addComponent(txt4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btn2)
                    .addGap(68, 68, 68))
            );

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

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

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

        private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    Livro livro = new Livro();
            
            livro.nome = (txt1.getText());
            livro.autor = (txt2.getText());
            livro.resumo = (txt3.getText());
            
            try{
                FileOutputStream arquivo = new FileOutputStream("livros.txt", true);
                PrintWriter pr = new PrintWriter(arquivo);
                
                pr.println(livro.nome + " | " + livro.autor + " | " + livro.resumo);
                
                pr.close();
                arquivo.close();
            }
            catch(Exception e){
                System.out.println("Erro ao escrever arquivo livros.txt");
            }
            
            txt1.setText("");
            txt2.setText("");
            txt3.setText("");
        }                                    

        private void txt1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
            // 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(CadastroAndPesquisa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(CadastroAndPesquisa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(CadastroAndPesquisa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(CadastroAndPesquisa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
            //</editor-fold>

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

        // Variables declaration - do not modify                     
        private javax.swing.JButton btn1;
        private javax.swing.JButton btn2;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JLabel lb1;
        private javax.swing.JLabel lb2;
        private javax.swing.JLabel lb3;
        private javax.swing.JLabel lb4;
        private javax.swing.JLabel lb5;
        private javax.swing.JLabel lb6;
        private javax.swing.JTextField txt1;
        private javax.swing.JTextField txt2;
        private javax.swing.JTextField txt3;
        private javax.swing.JTextField txt4;
        // End of variables declaration                   
    }

Se eu fosse você, não armazenaria as informações dos livros separadamente em um vetor, mas sim, armazenar o livro todo de uma vez só.

Sabe salvar Objeto em arquivo txt? Ou apenas sabe salvar dados que não são objetos?

Bom, eu pressuponho que seja a segunda opção.

Mas como que eu salvo um objeto em um arquivo .txt?
Na verdade você salvará um objeto em um arquivo .bin

Como fazer isso?
1)A classe que você quer salvar em um arquivo .bin, tem que implementar a interface Serializable, você não precisa implementar nenhum método, apenas a interface.
2)Ao invés de você usar o PrintWriter, você usará as classes ObjectOutputStream(para escrever no arquivo .bin) e ObjectInputStream(para ler o arquivo .bin)

Da uma pesquisada sobre essas duas classes.

OBS: Caso você decida criar uma classe Autor, e colocar a classe Autor como um atributo da classe Livro(ao invés de deixar como String, do qual não tem problema nenhum), a sua classe Autor terá que implementar a interface Serializable também

1 curtida

Entendi mais ou menos rs, vou dar uma estudava em OO e ver o que consigo.
Nesse caso, salvando .bin com ObjectOutputStream, como eu farei depois para pesquisar por exemplo o título dentro do arquivo.bin e puxar todas as informações referente ao mesmo (autor/resumo)?

Você não irá pesquisar o titulo, irá pegar o livro que está salvo no arquivo, e esse livro ja contêm essas informações.

Por sua sorte, tem um outro tópico recente falando sobre salvar objetos em arquivos, o tópico chama “Ajuda com serialização” da uma olhada, la ta mostrando o processo de escrever e ler o objeto.

1 curtida

Acho que entendi, vou pesquisar sobre

Obrigado.