I have a JTable
developed in Netbeans forms. I want the program to work in such a way that when I click a button, the new prepared records will be added to the existing ones. My problem is when I want to add new records, the moment I click the button, it replaces the existing one. Can anyone help me with the method to add new records to existing ones?
Use DefaultTableModel and simple call DefaultTableModel#addRow() method on it to add a new row.
sample code:
Object data[][] = { { "111 Hello", "Capital1", "TX 11111" },
{ "222 Hello", "Capital2", "TX 22222" },
{ "333 Hello", "Capital3", "TX 33333" },
{ "444 Hello", "Capital4", "TX 44444" }
};
String col[] = { "Name", "Capital", "TX" };
final DefaultTableModel model = new DefaultTableModel(data, col);
final JTable table = new JTable(model);
....
final JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Object[] newRecord = { "555 Hello", "Capital5", "TX 55555" };
model.addRow(newRecord); // <== Adding new row here
}
});
My problem is when I want to add new records, the moment i click the button, it replaces the existing one.
Don't create a new TableModel.
Instead you should be using the DefaultTableModel.addRow(...)
method to add a new row to the end of the table.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.