我创建了Jtable,用于存储数据库中的数据,我可以删除/添加内容'Jtable with Jbutton。当我尝试运行代码时,我得到了这个结果:
为什么会这样?
这里的代码我认为存在问题:
//add,delete button
final JToggleButton tglbtnAdd = new JToggleButton("Add");
final JToggleButton tglbtnDelete = new JToggleButton("Delete");
JButton button = new JButton("1");
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent arg0) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection dbconbt1 = DriverManager.getConnection("" +"jdbc:sqlserver://localhost;databaseName=Store;user=sa;password=");
Statement sqlstatement = dbconbt1.createStatement();
ResultSet dbresultset1 = sqlstatement.executeQuery("select * from Store.dbo.Product where ProductID = 'P-1'");
ResultSetMetaData rsmetadata = dbresultset1.getMetaData(); // Get metadata on them
int numcols = rsmetadata.getColumnCount(); // How many columns?
// Get column names
for (int i = 1; i <= numcols; i++) {
defaultmodel2.addColumn( rsmetadata.getColumnName(i));
}
if(tglbtnAdd.isSelected() == true) {
while (dbresultset1.next()) {
Vector<Object> row = new Vector<Object>(numcols);
for (int i = 1; i <= numcols; i++) {
row.addElement( dbresultset1.getObject(i) );
}
defaultmodel2.addRow(row );
}
}
if(tglbtnDelete.isSelected() == true) {
/**while (dbresultset1.next())
{
Vector<Object> row = new Vector<Object>(numcols);
row.removeElement( dbresultset1.getObject(0) );
}
*/
defaultmodel2.removeRow(0);
}
// Get row
dbresultset1.close();
sqlstatement.close();
dbconbt1.close();
答案 0 :(得分:0)
仅在表单加载时创建表结构,只需将JTextField
(或您使用的任何内容)中的数据转换为Object
数组。最后,将对象数组添加到模型中。要删除,只需调用model.removeRow()
方法即可。