RYN RYN - 3 years ago 103
Java Question

Disabling cell outline in JTable

I'm using a

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


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

enter image description here

How Can I disable this outline?

Answer Source

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(
                showFocusedCellBorder && hasFocus, // shall obviously always evaluate to false in this example
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download