Jonas
Jonas

Reputation: 128807

How can I focus on a whole row of a JTable?

I have a JTable that is showing some records in a Java Swing application. The user only works with whole rows, not with individual cells. Is there any way I can focus on a whole row of a JTable? The default is to focus only the cell that the user has clicked on. I use a different color for the focus, so it doesn't look good if only a cell is focused instead of the whole row.

UPDATE: This is my current code of my custom TableCellRenderer, the issue is that when a row has focus and is painted with the "focus" color, and then the JTable loses focus, only the cell that had focus is repainted with the "selected" color but all cells in the selected row should be repainted with the "selected" color.

@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;

}

Upvotes: 1

Views: 5150

Answers (2)

Howard
Howard

Reputation: 39197

A first idea would be something like

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

where I use my own logic to determine the focus based on the row attribute only. It uses the underlying cell renderers but looks strange if focus border is used.

Upvotes: 1

Pops
Pops

Reputation: 30828

Sounds like you're looking for the setRowSelectionAllowed() method.

Since you said just changing the color would be sufficient, you might want to look at the custom cell renderer section of the Swing Tutorial. You'd just have to set the logic to check on whether a given cell was in a selected row, and paint the background color accordingly.

Upvotes: 2

Related Questions