0
我有一個使用Eclipse創建的JTable,並使用Vector對象填充表。我希望數據庫(將數據提供給我的jtable)在對jtable進行更改後進行更新。我真的不知道我該怎麼做。一些建議? 我使用此代碼來填充的JTable:如何更新JTable中的數據? (帶代碼)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
import java.util.logging.Level;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
public class provemain2 {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new provemain2();
}
});
}
private final JButton button;
private final JTable table;
private final DefaultTableModel tableModel = new DefaultTableModel();
public provemain2() throws HeadlessException {
JFrame one =new JFrame();
one.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
one.setVisible(true);
table = new JTable(tableModel);
one.add(new JScrollPane(table), BorderLayout.CENTER);
button = new JButton("Load Data");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
loadData();
return null;
}
}.execute();
}
});
one.add(button, BorderLayout.PAGE_START);
one.setSize(640, 480);
}
private void loadData() {
//LOG.info("START loadData method");
button.setEnabled(false);
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root","psw");
Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from Acquirenti");
ResultSetMetaData metaData = rs.getMetaData();
// Names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnNames.add(metaData.getColumnName(i));
}
// Data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int i = 1; i <= columnCount; i++) {
vector.add(rs.getObject(i));
}
data.add(vector);
}
tableModel.setDataVector(data, columnNames);
} catch (Exception e) {
//LOG.log(Level.SEVERE, "Exception in Load Data", e);
}
button.setEnabled(true);
//LOG.info("END loadData method");
}
}
對不起,這個錯誤。 – Anptk 2014-09-27 10:27:19
編輯比道歉更好。噪音已刪除。 :) – 2014-09-27 10:40:07
由OP張貼的代碼是更好的,使用DefaultTableModel和正確的,問題是與EDT – mKorbel 2014-09-27 11:40:10