JTable.clearSelection () vs Jtable.getSelectionModel.clearSelection () - When to use what?

I need to undo all selections in a JTable model object. Java provides this "clearSelection ()" function, which does what I need, as far as I understand.

But I am confused why this function can be called in the JTable object, as well as in the selection model for the JTable object:

1) mytable.clearSelection(); 2) mytable.getSelectionModel().clearSelection(); 

Both methods work, but I don’t understand in what situation clearSelection () SelectionModel (e.g. 2)) makes sense. As far as I understand SelectionModels, they use to decide which choices JTable allows. I use SelectionModel to allow selection of only one row

 //allow only one row to be selected mytable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 

How should be preferred in which situation? Is there a good reason not to use method 1?

I would be glad if someone had a friendly explanation for this. thanks in advance.

+6
source share
2 answers

Here is the implementation of JTable#clearSelection()

 public void clearSelection() { selectionModel.clearSelection(); columnModel.getSelectionModel().clearSelection(); } 

As you can see, there are two ListSelectionModel that are cleared because you can select a column and / or row and / or cell.

From Oracle tutorial:

JTable uses a very simple selection concept, managed as the intersection of rows and columns. It was not intended to be a fully independent selection of cells.

A ListSelectionModel handles the entire aspect of the selection, for example, which row is selected, how we can select some rows, etc. Not just the kind of choice!
Learn more in the Oracle JTable Tutorial

+7
source

Usually, when you see two such methods, this is because the table calls the SelectionModel.clearSelection () method for you. Thus, the table method is a convenient method.

In this case, the actual code is:

 public void clearSelection() { selectionModel.clearSelection(); columnModel.getSelectionModel().clearSelection(); } 

Thus, both row and column selection models are cleared.

+5
source

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


All Articles