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:
See the program image:
IntheclickeventoftheAddbutton,anobjectoftypePessoa
isaddedtoJTable
andalsoto%typeofthisclass,see:
privatevoidbtnAddActionPerformed(java.awt.event.ActionEventevt){PessoapessoaAdd=newPessoa(txtNome.getText(),obtemIdAtual(tablePessoas));listaPessoas.add(pessoaAdd);addPessoaToJTable(tablePessoas,pessoaAdd);}
NotethatthereexiststheArrayList<T>
methodthatisresponsibleforgeneratingtheobtemIdAtual()
inasequentialway,andaslongasthevaluesoftheobjectsstoredinthevariableid
andthevaluesaddedtolistaPessoas
JTable
areidentical.
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?