java 将数据从 JDBC 显示到 JTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13685707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:36:16  来源:igfitidea点击:

Displaying data from JDBC into a JTable

javaswingjdbcjtable

提问by Matt C

I've followed some previous advice on this site about displaying database information in tables, however mine still won't work. I have a generated Netbeans Dialog with a table named mainTable, I am setting the Model to a ResultSet that has been taken from the MySql.

我遵循了本站点上有关在表格中显示数据库信息的一些先前建议,但是我的仍然无法正常工作。我有一个生成的 Netbeans 对话框,其中有一个名为 mainTable 的表,我将模型设置为从 MySql 中获取的 ResultSet。

EDIT the entire class:

编辑整个班级:

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........");
    }
}
}

And the DatabaseImpl class:

和 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;
}

However this just shows a blank area where the table should be, any help?

然而,这只是显示表格应该在的空白区域,有什么帮助吗?

The GUI class is a bog standard netbeans generated class.

GUI 类是沼泽标准的 netbeans 生成类。

回答by Hovercraft Full Of Eels

It looks like you're passing the TableModel into the wrong JTable, into one that is not being held by the currently visualized AddressBookGui instance. This won't work (as you're finding out) since setting the JTable of a newly created AddressBookGui instance will have absolutely no effect on the visualized object as while they are instances of the same class, they are independent of each other. The solution is to pass this model into the JTable that is held by the actually visualized AddressBookGui instance. Note a bad solution is to use static fields. Just don't do this.

看起来您将 TableModel 传递到错误的 JTable 中,传递到当前可视化的 AddressBookGui 实例未保存的 JTable 中。这将不起作用(正如您所发现的),因为设置新创建的 AddressBookGui 实例的 JTable 对可视化对象绝对没有影响,因为它们是同一类的实例,它们彼此独立。解决方案是将此模型传递到实际可视化的 AddressBookGui 实例所持有的 JTable 中。请注意,一个不好的解决方案是使用静态字段。不要这样做。

Edit
I think that your problem is with a convoluted misuse of inheritance and again of setting the model of a non-visualized JTable. I suspect that your line of code gui.main(null)calls a static main method that creates and displays an AddressBookGui instance, and that this guy holds your JFrame. If so, then again this AddressBookGui instance that it is displaying is notthe same as that held by the gui variable.

编辑
我认为您的问题在于对继承的复杂滥用以及再次设置非可视化 JTable 的模型。我怀疑您的代码行gui.main(null)调用了一个静态 main 方法,该方法创建并显示了一个 AddressBookGui 实例,而这个人持有您的 JFrame。如果是这样,那么这同样AddressBookGui实例它显示是一样的由GUI变量中。

I suggest that you not have AddressBookImpl extend AddressBookGui, but rather have it simply hold a instance of AddressBookGui, and that you not call AddressBookGui's main method but rather have AddressBookImpl be responsible for displaying itsAddressBookGui instance.

我建议您不要让 AddressBookImpl 扩展 AddressBookGui,而是让它只包含一个 AddressBookGui 的实例,并且您不要调用 AddressBookGui 的 main 方法,而是让 AddressBookImpl 负责显示AddressBookGui 实例。