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?
Asked
Active
Viewed 4,523 times
0

aterai
- 9,658
- 4
- 35
- 44

user3834805
- 11
- 1
- 1
-
1Hopefully this [answer](http://stackoverflow.com/a/24583025/1057230) along with the answers below, will help in your endeavour :-) – nIcE cOw Jul 16 '14 at 15:11
-
1Welcome to Stack Overflow! Before you post anymore questions, please carefully/thoroughly read **1.** [How to Ask](http://stackoverflow.com/help/how-to-ask). **2.** [Writing the Perfect Question](http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx) **3.** [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Paul Samsotha Jul 16 '14 at 18:53
2 Answers
3
Use DefaultTableModel and simple call DefaultTableModel#addRow() method on it to add a new row.
- Here table having 4 existing rows
- A new row is added on button click
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
}
});

Braj
- 46,415
- 5
- 60
- 76
-
I have followed your method but still when I click on the Jbutton, the it replaces the records in the first row without adding it as new records. I am using netbeans forms please help me – user3834805 Jul 16 '14 at 17:43
-
1have you tried with sample code that I shared you. Please first try it if this doesn't work then share your code in your original post. – Braj Jul 16 '14 at 17:44
2
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.

camickr
- 321,443
- 19
- 166
- 288