Disabling cell outline in JTable

I use JTable to display some data. The user can only select whole JTable rows, not individual cells. Here, the code is used to select only rows:

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

But when the user selects a row, the cell in this row is outlined (first column / last row in the image below):

enter image description here

How to disable this circuit?

+4
source share
2 answers

You can simply extend the DefaultTableCellRenderer and make it look from the interface that the cell is not “focused”.

I removed the border 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 install it on your JTable as follows:

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

or, for strings:

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

A little hack that it just reuses the original renderer and pretends that the focused / selected cell is not there, but it should start you.

+6
source

I just found a very simple trick to change this behavior. It turns out that focusing a cell is an extension of the focus of the tables. If the table cannot focus on individual cells (although the row selection is still displayed).

All you need is one simple line of code:

 jTable1.setFocusable(false); 

Here is an image from my project that implements the same behavior (Note: I use LookAndFeel windows)

Inactive cells

No matter which column you click under the entire row, it is selected, but the selected cell is not focused. I hope this helps! :)

0
source

Source: https://habr.com/ru/post/1442777/


All Articles