我正在尝试向JTable
添加多行。我有jTable1
并希望将一些结果添加到jTable2
。这是我的代码:
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);
}
第一行会添加很好,但是当我添加第二行时,它还会在右侧添加空白列,我尝试添加它的模式行将在侧面添加7个空白列。
答案 0 :(得分:2)
这是因为你不断向模型添加列
model.addColumn("id");
model.addColumn("miestas");
model.addColumn("adresas");
model.addColumn("pavadinimas");
model.addColumn("kaina");
model.addColumn("kiekis");
model.addColumn("data");
每次调用方法时重复
答案 1 :(得分:0)
你可以这样做
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);
}
}