[英]How to add new rows to existing rows in JTable
I have a JTable
developed in Netbeans forms. 我有一个以Netbeans形式开发的
JTable
。 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. 使用DefaultTableModel并对其简单调用DefaultTableModel#addRow()方法以添加新行。
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. 不要创建新的TableModel。
Instead you should be using the DefaultTableModel.addRow(...)
method to add a new row to the end of the table. 相反,您应该使用
DefaultTableModel.addRow(...)
方法将新行添加到表末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.