简体   繁体   English

Java Swing-向JTable添加行号列(行标题)

[英]Java Swing - Adding a row # column (row header) to a JTable

I have data from a database loaded into a JTable through a custom table model. 我通过自定义表模型将数据库中的数据加载到JTable中。 I want to have a column (should be the first column) which simply shows the display row number (ie it is not tied to any data (or sorting) but is simply the row number on the screen starting at 1). 我想有一列(应该是第一列),它只显示显示行号(即,它不与任何数据(或排序)绑定,而只是屏幕上从1开始的行号)。 These "row headers" should be grayed out like the row headers. 这些“行标题”应与行标题一样变灰。

Any idea how to do this? 任何想法如何做到这一点?

Thanks 谢谢

What TableModel are you using? 您正在使用什么TableModel?

You can override public Object getValueAt(int row, int column) to do this in your TableModel. 您可以在TableModel中重写public Object getValueAt(int row, int column)来执行此操作。

Ie

public Object getValueAt(int row, int column) {
    if(column == 1) {
        return row; 
    } ...
}

If that isn't working when you sort your JTable, then another solution is to implement it in a custom TableCellRenderer and override: 如果对JTable排序时这不起作用,则另一种解决方案是在自定义TableCellRenderer实现它并重写:

Component getTableCellRendererComponent(JTable table,
                                        Object value,
                                        boolean isSelected,
                                        boolean hasFocus,
                                        int row,
                                        int column)

If you want a row header that remains fixed in place when you do a horizontal scroll (like in Excel), then you could merge two JTables together. 如果希望行标题在进行水平滚动时(例如在Excel中)保持不变,则可以将两个JTable合并在一起。 This component shows you how its done : 该组件向您展示其完成方式:

http://blue-walrus.com/2014/12/row-number-column-in-jtable/ http://blue-walrus.com/2014/12/row-number-column-in-jtable/

您可能正在寻找此页面: http : //www.chka.de/swing/table/row-headers/JTable.html

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

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