简体   繁体   中英

Disabling cell outline in JTable

I'm using a JTable to show some data. The user can only select entire rows of the JTable , not individual cells. Here's the code used to allow only rows selection:

jTable1.setCellSelectionEnabled(false);
jTable1.setColumnSelectionEnabled(false);
jTable1.setRowSelectionAllowed(true);
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

But when a user selects a row the cell in that row gets outlined (first column / last row in the image below):

在此处输入图片说明

How Can I disable this outline?

You could simply extend the DefaultTableCellRenderer and pretend, from the UI's side, that the cell isn't "focused".

I removed the border by using the following renderer:

private static class BorderLessTableCellRenderer extends DefaultTableCellRenderer {

    private static final long serialVersionUID = 1L;

    public Component getTableCellRendererComponent(
            final JTable table,
            final Object value,
            final boolean isSelected,
            final boolean hasFocus,
            final int row,
            final int col) {

        final boolean showFocusedCellBorder = false; // change this to see the behavior change

        final Component c = super.getTableCellRendererComponent(
                table,
                value,
                isSelected,
                showFocusedCellBorder && hasFocus, // shall obviously always evaluate to false in this example
                row,
                col
        );
        return c;
    }
}

You can set it on your JTable like this:

table.setDefaultRenderer( Object.class, new BorderLessTableCellRenderer() );

or, for Strings:

table.setDefaultRenderer( String.class, new BorderLessTableCellRenderer() );

It's a bit of an hack in that it's simply reusing the original renderer and pretending that the focused/selected cell isn't but it should get you started.

I just found a very simple trick to alter this behaviour. It turns out that cell focusing is an extension of the tables focus. If the table can not be focused on neither can individual cells (though row selections still show up).

All you need is one simple line of code:

jTable1.setFocusable(false);

Here is a picture from a project of mine that implements this same behaviour (Note: I am using windows LookAndFeel)

不可聚焦细胞

Regardless of which column you click under the entire row is selected but the cell you clicked is not focused. I hope it 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