使用数据库数据填充jTable [英] Populating jTable using database data

查看:78
本文介绍了使用数据库数据填充jTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用我的Derby数据库数据填充Netbeans GUI-builder jTable。

I am trying to populate a Netbeans GUI-builder jTable using my Derby database data.

我在我的Account.java类中使用以下代码:

I am using the following code, in my Account.java class:

public DefaultTableModel getData() {
    try {
        String stmt = "SELECT * FROM APP.DATAVAULT";
        PreparedStatement ps = Main.getPreparedStatement(stmt);
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount();
        Vector columns = new Vector(columnCount);
        //store column names  
        for (int i = 1; i <= columnCount; i++) {
            columns.add(md.getColumnName(i));
        }

        Vector data = new Vector();
        Vector row;
        while (rs.next()) {

            row = new Vector(columnCount);
            for (int i = 1; i <= columnCount; i++) {
                row.add(rs.getString(i));
            }
            data.add(row);

            //Debugging                
        }

        // List.setModel(tableModel);

        ps.close();
        rs.close();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
    DefaultTableModel tableModel = new DefaultTableModel(data, columns);
    return tableModel;
}

理想情况下,我希望能够使用参数data返回tableModel里面的列,据我所知在我的GUI中做这个方法是不好的做法。所有在线教程都没有显示如何将数据发送到另一个类,他们只是在GUI类中执行数据库代码。

Ideally, I want to be able to return the tableModel with the parameters data and columns inside, as I understand doing this method within my GUI is bad practice. All tutorials online do not show how to send the data across to another class, they just do the database code within the GUI classes.

我有一个错误,它看不到数据和列,因为它们是在我方法的无法访问的部分中声明和使用的。完成此操作后,我需要找到一种方法将其传递到我的GUI类并为我的jTable设置模型,该模型由Netbeans GUI builder制作。

I have an error where it cannot see data and columns because they are declared and used in an unreachable part of my method. After I've done this, I need to find a way of getting this across to my GUI class and setting the model for my jTable which was made by Netbeans GUI builder.

我一直在搜索这个网站的答案,我尝试了很多解决方案。但是,由于我编写系统的方式,我似乎从未得到任何工作。我还尝试过其他网站,例如:

I have been searching this website for answers and I have tried many solutions. However, I never seem to get anything to work due to the way I have coded my system. I have also tried other websites such as:

http://tips4java.wordpress.com/2009/03/12/table-from-database/

< a href =http://chang.advits.com/populate-data-from-database-into-jtable-in-netbeans =nofollow> http://chang.advits.com/populate-data- from-database-into-jtable-in-netbeans <这本来是理想的,但它不起作用。我跟着它去了一个发球台!

http://chang.advits.com/populate-data-from-database-into-jtable-in-netbeans < this would have been ideal but it did not work. I followed it to a tee!

并查看了javadocs的jTad,DefaultTableModel和ResultSetTableModel - 我绝对没有试过通过学习等自己做这个。 。

and have looked at the Javadocs for jTable, DefaultTableModel and ResultSetTableModel - I have by no means not tried doing this myself by learning etc...

我如何通过建模系统的方式来实现这一目标?另外,无论如何修复我的方法还是应该完全废弃它?

How can I go about doing this with the way I have modelled my system? Also, anyway of fixing my method or should I scrap it altogether?

推荐答案

因此,您需要一些方法来告诉表格已加载模型。您可以使用侦听器回调机制,但可能更容易使用 SwingWorker

So, you need some way to "tell" the table that the model has been loaded. You could use a listener call back mechanism, but it might be easier to use a SwingWorker instead.

这将是允许您在后台线程中调用数据库,当它完成时,从EDT中更新UI。

This will allow you to make a call to the database in a background thread and when it's finished, update the UI from within the EDT.

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import sun.applet.Main;

public class DataLoadWorker extends SwingWorker<TableModel, TableModel> {

    private final JTable table;

    public DataLoadWorker(JTable table) {
        this.table = table;
    }

    @Override
    protected TableModel doInBackground() throws Exception {
        Vector data = new Vector();
        Vector columns = new Vector();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String stmt = "SELECT * FROM APP.DATAVAULT";
            ps = Main.getPreparedStatement(stmt);
            rs = ps.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            //store column names  
            for (int i = 1; i <= columnCount; i++) {
                columns.add(md.getColumnName(i));
            }

            columns.ensureCapacity(columnCount);

            Vector row;
            while (rs.next()) {

                row = new Vector(columnCount);
                for (int i = 1; i <= columnCount; i++) {
                    row.add(rs.getString(i));
                }
                data.add(row);

                //Debugging                
            }

            // List.setModel(tableModel);

        } finally {
            try {
                ps.close();
            } catch (Exception e) {
            }
            try {
                rs.close();
            } catch (Exception e) {
            }
        }

        DefaultTableModel tableModel = new DefaultTableModel(data, columns);
        return tableModel;
    }

    @Override
    protected void done() {
        try {
            TableModel model = get();
            table.setModel(model);
        } catch (InterruptedException | ExecutionException ex) {
            ex.printStackTrace();
        }
    }
}

你的榜样无论如何工作。

You're example won't work either.

Vector s 和使用 try-catch 的上下文声明 data ,这意味着它们的剩余部分将不会显示方法,所以 DefaultTableModel tableModel = new DefaultTableModel(data,columns); 将无法编译。

The Vectors columns and data are declared withing the context of the try-catch, which means they won't be visible to the remainder of the method, so DefaultTableModel tableModel = new DefaultTableModel(data, columns); won't compile.

你应该至少,转储任何异常的堆栈跟踪,它将帮助您找到实际错误的位置,因此而不是 System.out.println(e.getMessage()); ,你应该使用 e.printStackTrace(); 。更好的解决方案是使用JDK或第三方记录器 log4j 中的 Logger

You should be, at the very least, dumping the stack trace of any exceptions, it will help you find where the actually error is, so instead of System.out.println(e.getMessage());, you should use e.printStackTrace();. A better solution is to use the Logger either from the JDK or a third party logger like log4j.

您也是资源,也就是说,如果您打开,您应该关闭它。当你打电话给 ps.close() rs.close()时,如果由于某种原因,异常发生时,它们不会被调用,而是打开资源。

You are also resources, that is, if you open, you should close it. While you do call ps.close() and rs.close(), if, for what ever reason, an exception occurs, they will not be called, leaving resources open.

将这些添加到 finally try-catch 确保关闭它们并尽最大努力关闭它们。

Add these to the finally block of your try-catch to ensure that they are closed and make all best efforts to close them.

这篇关于使用数据库数据填充jTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆