我已经遵循了该站点上有关在表中显示数据库信息的一些先前建议,但是我的仍然无法正常工作。我有一个生成的 Netbeans 对话框,其中包含一个名为 mainTable 的表,我将模型设置为从 MySql 获取的 ResultSet。
编辑整个班级:
import swing.SwingUtilities;
import javax.java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
swing.table.DefaultTableModel;
public class AddressBookImpl extends AddressBookGui implements ActionListener {
final static AddressBookImpl impl = new AddressBookImpl();
DefaultTableModel defaultTableModel = new DefaultTableModel();
AddressBookGui gui = new AddressBookGui();
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() { impl.startGUI(); }});
}
public void startGUI(){
gui.main(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setResizable(true);
this.setTitle("Address Book");
listeners();
refreshTable();
}
public DefaultTableModel refreshTable() {
try{
DatabaseImpl dbimpl = new DatabaseImpl();
dbimpl.refreshDatabase();
ResultSet refreshResult = dbimpl.refreshResult;
ResultSetMetaData meta = refreshResult.getMetaData();
int numberOfColumns = meta.getColumnCount();
while (refreshResult.next())
{
Object[] rowData = new Object[numberOfColumns];
for (int i = 0; i < rowData.length; ++i)
{
rowData[i] = refreshResult.getObject(i + 1);
}
defaultTableModel.addRow(rowData);
}
this.defaultTableModel = defaultTableModel;
} catch (Exception e) {
e.printStackTrace();
}
gui.mainTable.setModel(defaultTableModel);
return defaultTableModel;
}
public void listeners() {
quitFileMenuBar.addActionListener(this);
addButton.addActionListener(this);
refreshButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("Quit"))
{
this.dispose();
}
if (e.getActionCommand().equalsIgnoreCase("Add"))
{
// Add a new address to the DB
}
if (e.getActionCommand().equalsIgnoreCase("About"))
{
}
if (e.getActionCommand().equalsIgnoreCase("Refresh"))
{
refreshTable();
System.out.println("Refreshing........");
}
}
}
和 DatabaseImpl 类:
protected ResultSet refreshDatabase() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
System.out.println("Connection is created to " + url);
Statement statement = con.createStatement();
String selectAllQuery = "Select * from " + table + ";";
ResultSet refreshResult = statement.executeQuery(selectAllQuery);
// con.close();
this.refreshResult = refreshResult;
return refreshResult;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return refreshResult;
}
然而,这只是显示了表格应该在的空白区域,有什么帮助吗?
GUI 类是一个沼泽标准 netbeans 生成的类。