2011-03-31 43 views
1

我有一个JTable显示Java Swing应用程序中的一些记录。用户只能使用整行,而不是单个单元。有什么办法可以专注于JTable的整行?默认设置是只关注用户点击的单元格。我为焦点使用了不同的颜色,所以如果只有一个细胞聚焦而不是整行,它看起来不太好。如何关注一整行JTable?

UPDATE:这是我目前我的自定义TableCellRenderer的代码,问题是,当行具有焦点,并绘有“焦点访谈”的颜色,然后JTable失去焦点,只有细胞那焦点重新用“选定”颜色重新绘制,但选定行中的所有单元格都应使用“选定”颜色重新绘制。

@Override 
public Component getTableCellRendererComponent(JTable table, 
     Object value, boolean isSelected, boolean hasFocus, 
     int row, int column) { 

    // Has any cell in this row focus? 
    if(table.getSelectedRow() == row && table.hasFocus()) { 
     hasFocus = true; 
    } 

    if (hasFocus) { 
     this.setBackground(CustomColors.focusedColor); 
    } else if (isSelected) { 
     this.setBackground(CustomColors.selectedColor); 
    } else { 

     // alternate the color of every second row 
     if(row % 2 == 0) { 
      this.setBackground(Color.WHITE); 
     } else { 
      this.setBackground(CustomColors.grayBg); 
     } 
    } 

    setValue(value); 

    return this; 

} 
+0

是否足以使用自定义cellrenderer来显示行中的所有单元格,因为它们将具有焦点? – Howard 2011-03-31 16:39:15

+0

@霍华德:是的,如果你有建议,那就足够了。 – Jonas 2011-03-31 16:48:05

+0

另请参阅[表格行渲染](http://tips4java.wordpress.com/2010/01/24/table-row-rendering/)。 – trashgod 2011-04-01 02:57:40

回答

2

听起来像是你在找the setRowSelectionAllowed() method

既然你说过只是改变颜色就足够了,你可能想看看Swing教程的custom cell renderer section。您只需设置逻辑以检查给定单元格是否位于选定行中,并相应地绘制背景颜色。

+0

没关系,我在考虑选择,而不是专注。 – Pops 2011-03-31 16:44:20

+0

这是一个很好的建议,但我有一个问题。当JTable失去焦点时,只有被聚焦的单元格被重新绘制(使用“selected”颜色),并且该行上的其他单元格仍然具有“聚焦”的颜色,因为它们没有被重新绘制。有什么建议么? – Jonas 2011-03-31 17:16:20

+0

@Jonas,让渲染器明确地设置所有不在选定行的单元格上的“普通”背景颜色,而不是忽略它们。 – Pops 2011-03-31 17:24:06

1

第一个想法是像

JTable jTable = new JTable() { 
    public TableCellRenderer getCellRenderer(int row, int column) { 
     final TableCellRenderer superRenderer = super.getCellRenderer(row, column); 
     return new TableCellRenderer() { 

      @Override 
      public Component getTableCellRendererComponent(JTable table, Object object, boolean isSelected, boolean hasFocus, int row, int column) { 
       // determine focus on row attribute only 
       hasFocus = hasFocus() && isEnabled() && getSelectionModel().getLeadSelectionIndex() == row; 
       return superRenderer.getTableCellRendererComponent(table, object, isSelected, hasFocus, row, column); 
      } 
     }; 
    } 
}; 

,我用我自己的逻辑来确定基于行的焦点只读属性。它使用基础的单元格渲染器,但使用焦点边框时看起来很奇怪。

+0

谢谢,但我认为这与我在我更新的问题中发布的代码具有相同的问题。当'JTable'失去焦点时,只有具有焦点的单元格被重新绘制。所以行中的其他单元格仍将具有“焦点”颜色。 – Jonas 2011-03-31 17:34:29