Reputation: 27
I'm trying to add multiple rows to a JTable
. I've got jTable1
and want to add some results to jTable2
. Here is my code:
DefaultTableModel model = new DefaultTableModel();
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
model.addColumn("id");
model.addColumn("miestas");
model.addColumn("adresas");
model.addColumn("pavadinimas");
model.addColumn("kaina");
model.addColumn("kiekis");
model.addColumn("data");
int i=jTable1.getSelectedRow();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
jXDatePicker1.setFormats(dateFormat);
String date = dateFormat.format(jXDatePicker1.getDate()).toString();
String c1=jTable1.getValueAt(i, 0).toString();
String c2=jTable1.getValueAt(i, 1).toString();
String c3=jTable1.getValueAt(i, 2).toString();
String c4=jTable1.getValueAt(i, 3).toString();
String c5=price.getText().toString();
String c6=jTextField1.getText().toString();
String c7=date;
model.addRow(new Object[]{c1, c2, c3, c4, c5, c6, c7});
jTable2.setModel(model);
}
The first row would add just fine, but when I add the second one it also add blank columns on right side, the mode rows I try to add it would add 7 blank columns on side.
Upvotes: 0
Views: 1180
Reputation: 73
You can do this
public class ClassName {
String[] columns = {"ID", "miestas", "adresas", "pavadinimas", "kaina", "kiekis", "data"};
DefaultTableModel model;
public ClassName() {
model = new DefaultTableModel(columns, 0); //sets columns and number of rows once
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
int i = jTable1.getSelectedRow();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
jXDatePicker1.setFormats(dateFormat);
String date = dateFormat.format(jXDatePicker1.getDate()).toString();
String c1 = jTable1.getValueAt(i, 0).toString();
String c2 = jTable1.getValueAt(i, 1).toString();
String c3 = jTable1.getValueAt(i, 2).toString();
String c4 = jTable1.getValueAt(i, 3).toString();
String c5 = price.getText().toString();
String c6 = jTextField1.getText().toString();
String c7 = date;
model.addRow(new Object[]{c1, c2, c3, c4, c5, c6, c7});
jTable2.setModel(model);
}
}
Upvotes: 0
Reputation: 297
That is because you keep adding columns to the model
model.addColumn("id");
model.addColumn("miestas");
model.addColumn("adresas");
model.addColumn("pavadinimas");
model.addColumn("kaina");
model.addColumn("kiekis");
model.addColumn("data");
Repeats each time you call the method
Upvotes: 2