简体   繁体   中英

Both row and column selection on JTable

When I click on a JTable cell I'd like to select its whole row and its whole column.

I tried to setRowSelectionAllowed(true) and setColumnSelectionAllowed(true) and then specified a selectionInterval but it select only the single cell!

How can I do that?

You might be able to provide your own custom highlighting of the cells.

Check out Table Row Rendering for an example of how this is done at the row level.

You could see if this approach will also work at the column level. The major concern is that as column selection changes, the entire previous column will also need to be repainted. Not sure how a JTable currently handles this.

As @camickr has pointed out, you might need to use table rendering to do this. This might not be the best answer but this is what I can come up with:

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        if (column == table.getSelectedColumn()) {
            c.setBackground(new Color (57, 105, 138));
            c.setForeground(Color.white);
        } else if (row == table.getSelectedRow()) {
            c.setBackground(new Color (57, 105, 138));
            c.setForeground(Color.white);
        } else {
            if (row % 2 == 0) {
                c.setBackground(Color.white);
                c.setForeground(Color.black);
            } else {
                c.setBackground(new Color(242, 242, 242));
                c.setForeground(Color.black);
            }
        }

        return c;
    }
});

The new Color(57, 105, 138) is my default JTable selected color (I don't know if it's different with different jdk versions). The colors in the else statement are my default JTable not selected colors. Also, add repaint() method in your listener. Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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