[英]How can I focus on a whole row of a JTable?
我有一個JTable
,它顯示Java Swing應用程序中的一些記錄。 用戶僅處理整行,而不處理單個單元格。 有什么辦法可以專注於JTable
的整行嗎? 默認設置是僅集中用戶單擊的單元格。 我對焦點使用了不同的顏色,因此,如果僅對一個單元格而不是整個行進行聚焦,效果會不佳。
更新:這是我自定義TableCellRenderer
當前代碼,問題是當一行具有焦點並用“ focus”顏色繪制時, JTable
失去焦點,只有具有焦點的單元格才用“ selected”重新繪制顏色,但選定行中的所有單元格都應使用“選定”顏色重新繪制。
@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;
}
聽起來您正在尋找setRowSelectionAllowed()
方法 。
因為您說過僅更改顏色就足夠了,所以您可能需要查看Swing教程的“ 自定義單元格渲染器”部分 。 您只需要設置邏輯以檢查給定單元格是否在所選行中,並相應地繪制背景顏色。
第一個想法是
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);
}
};
}
};
我使用自己的邏輯僅根據row屬性確定焦點。 它使用基礎單元格渲染器,但如果使用焦點邊框,則看起來很奇怪。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.