Java 在 JTable 中显示行号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20065477/
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-08-12 22:48:30  来源:igfitidea点击:

Displaying row numbers in JTable

javaswingjtablerowheader

提问by miles

hi I have this jtable which I want to have its auto increment row header for the user to identify how many data does the table returned. I am actually getting the table model from result set and the data is not fixed. It vary depends on the search of the user.

嗨,我有这个 jtable,我想要它的自动增量行标题供用户识别表返回了多少数据。我实际上是从结果集中获取表模型并且数据不是固定的。它因用户的搜索而异。

Here's my table model code:

这是我的表模型代码:

public void retrieveMember() throws SQLException {
     mDao.dbConnect();
        try {

        if(mDao.con!=null)
        {  
   mDao.ps = mDao.con.prepareStatement(this.getSql());
   mDao.rs = mDao.ps.executeQuery();
   this.tblGender.setModel(DbUtils.resultSetToTableModel(mDao.rs));

    int[] columnsWidth = { 100, 150, 150, 300, 50, 60, 100, 100, 125,65};
    int i = 0;
    for (int width : columnsWidth) {
        TableColumn column =this.tblGender.getColumnModel().getColumn(i++);
        column.setMinWidth(width);
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
    }

   } else
        {
              System.out.println("Con is null");
        }

    } catch (SQLException ex) {
        ex.printStackTrace();
        throw ex;


    }
  }

Can anyone help me to put an auto increment row header? Something that will display how many data does my table returning.

谁能帮我放一个自动增量行标题?将显示我的表返回多少数据的东西。

            -------------------------
                  Name| Age | Gender
            -------------------------
               1| Nely| 16  |Female
               2| Amy | 18  |Female

thank you in advance.

先感谢您。

回答by Jason C

Perhaps one of these options, if modifying the original table model is not possible:

也许这些选项之一,如果修改原始表模型是不可能的:

I recommend the first option. It is straightforward and can be used in many situations.

我推荐第一个选项。它很简单,可以在许多情况下使用。

回答by rachana

Try this :

尝试这个 :

If number of columns are fix for your table then you can take the counter to get the total number of rows return by table in database.

如果您的表的列数是固定的,那么您可以使用计数器来获取数据库中表返回的总行数。

 mDao.rs = mDao.ps.executeQuery();
 int count = 0;

    /** Setting table fields values **/
    if( mDao.rs.next())
        table.setValueAt( mDao.rs.getString("Name"),count,0);
        table.setValueAt(mDao.rs.getInt("Age"),count,1);
        table.setValueAt(mDao.rs.getString("Gender"),count,2);
        count++;
    }

Count will give the no of record return by table.

Count 将给出按表返回的记录数。