如何将 DefaultTableModel 对象的数据放入 DefaultTableModel 的子类中 [英] How to get a DefaultTableModel object's data into a subclass of DefaultTableModel

查看:25
本文介绍了如何将 DefaultTableModel 对象的数据放入 DefaultTableModel 的子类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 jTable 显示一个简单的两列 sql 表的数据并允许用户维护列表.这是我的第一个java程序.让用户可以编辑数据列表并按保存进行更新.我从这行代码中获取到 jTable 的 DefaultTableModel 的 sql 数据:

I have a jTable displaying a simple two column sql table's data and allowing a user to maintain the list. This is my first java program. 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:

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

我猜这里的人对 DBUtils 和 resultSets 很熟悉.我想为每一行添加一个复选框.看这里和其他地方,我一直看到子类 DefaultTableModel 以便重写一个方法:

I'm guessing DBUtils and resultSets are familiar to people here. I want to add a CheckBox to each row. Looking here and elsewhere I kept seeing to subclass DefaultTableModel in order to override a method thus:

/*

  * 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();
   }

但是,我不知道如何将 DefaultTableModel 的输出从 resultSetToTableModel 方法获取到我的子类 - 如果 SetTableModel 方法更改为接受子类作为其参数,则显示的语句不会编译.有没有我想念的简单方法?

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. Is there an easy way I'm missing?

推荐答案

这是一个示例,展示了如何从 ResultSet 读取数据并在您的应用程序中实现 getColumnClass(...) 方法自己的自定义 DefaultTableModel:

Here is an example that shows how to read the data from the ResultSet and implement the getColumnClass(...) method in your own custom DefaultTableModel:

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

通过覆盖 getColumnClass(...) 方法,您现在将看到数字格式右对齐,如果您需要对数据进行排序,它将正常工作,因为该列将根据数值不是字符串值.

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.

我想为每一行添加一个复选框.

I want to add a CheckBox to each row.

所以现在你有两个选择:

So now you have two options:

  1. 修改上面的代码,使columnNames"Vector 包含复选框列的另一个标题名称,并在遍历 ResultSet 时将 Boolean.FALSE 添加到每个行"Vector.

  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.

按原样使用上面的 TableModel(或使用 DbUtils TableModel),然后创建一个包装 TableModel,它将向任何现有的 TableModel 添加一个复选框列.查看:如何在填充的 Jtable 中添加复选框使用 rs2xml 作为这种方法的示例.

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. Check out: How to add checkbox in Jtable populated using rs2xml for an example of this approach.

这篇关于如何将 DefaultTableModel 对象的数据放入 DefaultTableModel 的子类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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