How do I make the JTable values the same as the ArrayListPessoa?

9

I have an example program that adds objects of the type of my class Pessoa to a JTable and also to ArrayList<T> , this program has three basic functionalities which are as follows:

  • Add
  • Change
  • Delete
  • See the program image:

    IntheclickeventoftheAddbutton,anobjectoftypePessoaisaddedtoJTableandalsoto%typeofthisclass,see:

    privatevoidbtnAddActionPerformed(java.awt.event.ActionEventevt){PessoapessoaAdd=newPessoa(txtNome.getText(),obtemIdAtual(tablePessoas));listaPessoas.add(pessoaAdd);addPessoaToJTable(tablePessoas,pessoaAdd);}

    NotethatthereexiststheArrayList<T>methodthatisresponsibleforgeneratingtheobtemIdAtual()inasequentialway,andaslongasthevaluesoftheobjectsstoredinthevariableidandthevaluesaddedtolistaPessoasJTableareidentical.

    Reproducingtheexample

    ToreproducethisexampleyouwillneedthecodeofthePersonclassandalsothecodecorrespondingtothescreenoftheprogramaretwofiles.Herearethecompletecodesbelow.

    Personclasscode:

    packageaquicolocaseupacote;publicclassPessoa{privateStringnome;publicStringgetNome(){returnnome;}publicvoidsetNome(Stringnome){this.nome=nome;}privateintid;publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}publicPessoa(){}publicPessoa(Stringnome,intid){this.nome=nome;this.id=id;}}

    ScreencodeMainExample:

    packageaquicolocaseupacote;importjava.awt.EventQueue;importjava.util.ArrayList;importjava.util.List;importjavax.swing.JFrame;importjavax.swing.JTable;importjavax.swing.table.DefaultTableModel;publicclassMainExemploextendsJFrame{privateList<Pessoa>listaPessoas=newArrayList<>();publicMainExemplo(){initComponents();}@SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            btnApagar = new javax.swing.JButton();
            btnAlterar = new javax.swing.JButton();
            btnAdd = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            tablePessoas = new javax.swing.JTable();
            jLabel1 = new javax.swing.JLabel();
            txtNome = new javax.swing.JTextField();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Exemplo");
            setResizable(false);
    
            btnApagar.setText("Apagar");
            btnApagar.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnApagarActionPerformed(evt);
                }
            });
    
            btnAlterar.setText("Alterar");
            btnAlterar.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnAlterarActionPerformed(evt);
                }
            });
    
            btnAdd.setText("Add");
            btnAdd.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnAddActionPerformed(evt);
                }
            });
    
            tablePessoas.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
    
                },
                new String [] {
                    "Id", "Nome"
                }
            ) {
                boolean[] canEdit = new boolean [] {
                    false, false
                };
    
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            });
            jScrollPane1.setViewportView(tablePessoas);
    
            jLabel1.setText("Nome:");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(btnAdd)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(btnAlterar)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(btnApagar)
                                    .addGap(0, 46, Short.MAX_VALUE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(txtNome)))))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(9, 9, 9)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnApagar)
                        .addComponent(btnAlterar)
                        .addComponent(btnAdd))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            pack();
            setLocationRelativeTo(null);
        }// </editor-fold>                        
    
        private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
            Pessoa pessoaAdd = new Pessoa(txtNome.getText(), obtemIdAtual(tablePessoas));
            listaPessoas.add(pessoaAdd);
            addPessoaToJTable(tablePessoas, pessoaAdd);
        }                                      
    
        private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {                                           
            switch (btnAlterar.getText()) {
                case "Alterar":
                    btnAdd.setEnabled(false);
                    btnAlterar.setText("Salvar");
                    break;
                case "Salvar":
                    btnAdd.setEnabled(true);
                    btnAlterar.setText("Alterar");
                    break;
            }
        }                                          
    
        private void btnApagarActionPerformed(java.awt.event.ActionEvent evt) {                                          
    
        }                                         
    
        void addPessoaToJTable(JTable jTable, Pessoa pessoa) {
            DefaultTableModel model = (DefaultTableModel) jTable.getModel();        
            model.addRow(new Object[] { pessoa.getId(), pessoa.getNome() });
        }
    
        int obtemIdAtual(JTable jTable) {
            DefaultTableModel model = (DefaultTableModel) jTable.getModel();
    
            if (model.getRowCount() > 0) {
                return  (Integer) model.getValueAt(model.getRowCount() - 1, 0) + 1;
            }
            else {
                return 1;
            }
        }
    
        public static void main(String args[]) {                      
            EventQueue.invokeLater(() -> { 
                new MainExemplo().setVisible(true); 
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.JButton btnAdd;
        private javax.swing.JButton btnAlterar;
        private javax.swing.JButton btnApagar;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable tablePessoas;
        private javax.swing.JTextField txtNome;
        // End of variables declaration                   
    }
    

    My difficulty

    I'm not able to implement the Change button routine and neither of the Delete button, that is, when the user makes a change by clicking on the change the value (object of type Person) must be changed in both the object that is in the tablePessoas variable and in the JTable listaPessoas and the same is true for the delete button.

    I would like to know how I could do this implementation as described above?

        
    asked by anonymous 18.10.2016 / 23:25

    1 answer

    9

    Implement the setValueAt() and getColumnClass methods in the TableModel , so that Jtable knows exactly what kind of data exists in each column, and what to do with them when the table suffers change.

    But to make it easier to maintain the code in your table, it would be ideal to create a TableModel itself instead of using DefaultTableModel , because in this way you abstract from the class of your screen and the table itself, functionalities model, how to remove and add new objects. I usually always need to do a table in the

    18.10.2016 / 23:46