简体   繁体   English

如何将DefaultTableModel对象的数据获取到DefaultTableModel的子类中

[英]How to get a DefaultTableModel object's data into a subclass of DefaultTableModel

I have a jTable displaying a simple two column sql table's data and allowing a user to maintain the list. 我有一个jTable显示一个简单的两列sql表的数据,并允许用户维护该列表。 This is my first java program. 这是我的第一个Java程序。 Have that working such that user can edit the list of data and press save to update. 运行该功能,以便用户可以编辑数据列表,然后按保存进行更新。 I get the sql data to the jTable's DefaultTableModel from this line of code: 我从以下代码行将sql数据获取到jTable的DefaultTableModel中:

paCutAboveTable.SetTableModel((DefaultTableModel) DbUtils.resultSetToTableModel(rs));

I'm guessing DBUtils and resultSets are familiar to people here. 我猜这里的人熟悉DBUtils和resultSets。 I want to add a CheckBox to each row. 我想向每行添加一个CheckBox。 Looking here and elsewhere I kept seeing to subclass DefaultTableModel in order to override a method thus: 在这里和其他地方,我一直在寻找DefaultTableModel的子类,以便因此重写方法:

/*

  * JTable uses this method to determine the default renderer/
  * editor for each cell.  If we didn't implement this method,
  * then the last column would contain text ("true"/"false"),
  * rather than a check box.
  */

 public Class getColumnClass(int c) {

     return getValueAt(0, c).getClass();
   }

However I can't figure how to get the output of DefaultTableModel from resultSetToTableModel method to my subclass - the statement shown doesn't compile if the SetTableModel method is changed to accept the subclass as its parameter. 但是我不知道如何将DefaultTableModel的输出从resultSetToTableModel方法传递到我的子类-如果将SetTableModel方法更改为接受子类作为其参数,则显示的语句不会编译。 Is there an easy way I'm missing? 有没有一种简单的方法我想念的?

Here is an example that shows how to read the data from the ResultSet and implement the getColumnClass(...) method in your own custom DefaultTableModel: 以下示例显示了如何从ResultSet中读取数据并在自己的自定义DefaultTableModel中实现getColumnClass(...)方法:

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableFromDatabase extends JFrame
{
    public TableFromDatabase()
    {
        Vector<Object> columnNames = new Vector<Object>();
        Vector<Object> data = new Vector<Object>();

        try
        {
            //  Connect to an Access Database

            String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
//            String url = "jdbc:odbc:???";  // if using ODBC Data Source name
            String url =
                "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/directory/???.mdb";
            String userid = "";
            String password = "";

            Class.forName( driver );
            Connection connection = DriverManager.getConnection( url, userid, password );

            //  Read data from a table

            String sql = "Select * from ???";
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery( sql );
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names

            for (int i = 1; i <= columns; i++)
            {
                columnNames.addElement( md.getColumnLabel(i) );
            }

            //  Get row data

            while (rs.next())
            {
                Vector<Object> row = new Vector<Object>(columns);

                for (int i = 1; i <= columns; i++)
                {
                    row.addElement( rs.getObject(i) );
                }

                data.addElement( row );
            }

            rs.close();
            stmt.close();
            connection.close();
        }
        catch(Exception e)
        {
            System.out.println( e );
        }

        //  Create table with database data

        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {
            @Override
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                    {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JTable table = new JTable( model );
        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );

        JPanel buttonPanel = new JPanel();
        add( buttonPanel, BorderLayout.SOUTH );
    }

    public static void main(String[] args)
    {
        TableFromDatabase frame = new TableFromDatabase();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    }
}

By overriding the getColumnClass(...) method you will now see number formatted right aligned and if you ever need to sort the data it will work properly since the column will be sorted based on a numeric value not a String value. 通过覆盖getColumnClass(...)方法,您现在将看到数字格式正确对齐,并且如果您需要对数据进行排序,它将可以正常工作,因为该列将基于数字值而不是String值进行排序。

I want to add a CheckBox to each row. 我想向每行添加一个CheckBox。

So now you have two options: 因此,您现在有两个选择:

  1. Modify the above code so that the "columnNames" Vector contains another header name for the check box column and add Boolean.FALSE to each "row" Vector as you iterate through the ResultSet. 修改上面的代码,以使“ columnNames”向量包含复选框列的另一个标题名称,并在遍历ResultSet时向每个“行”向量添加Boolean.FALSE

  2. Use the above TableModel as is (or use the DbUtils TableModel) and then create a wrapper TableModel that will add a check box column to any existing TableModel. 按原样使用上面的TableModel(或使用DbUtils TableModel),然后创建包装器TableModel,该包装器将在任何现有TableModel中添加一个复选框列。 Check out: How to add checkbox in Jtable populated using rs2xml for an example of this approach. 出: 如何在使用rs2xml填充的Jtable中添加复选框,以获取此方法的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM