Allowing users to select individual non-continuous cells in a JTable provides greater flexibility and user convenience. Here's how you can achieve this:
If you want to enable non-continuous cell selection without remembering the last selected cell, simply hold down the CTRL key while clicking on the desired cells. This method allows for easy and direct cell selection without modifying the default JTable behavior.
Alternatively, you can implement a custom ListSelectionModel that supports non-continuous cell selection. This is necessary when you require specific control over the selection process, such as maintaining the last selected cell or implementing custom selection rules.
The following code demonstrates the use of a custom ListSelectionModel for non-continuous cell selection in a JTable:
import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class NonContinuousSelectionModel extends DefaultListSelectionModel { @Override public boolean isSelectedIndexSelected(int index) { boolean selected = super.isSelectedIndexSelected(index); if (selected) { return true; } int minIndex = getMinSelectionIndex(); int maxIndex = getMaxSelectionIndex(); if (minIndex == -1) { return false; } if (index < minIndex || index > maxIndex) { return false; } for (int i = minIndex; i <= maxIndex; i++) { if (i == index) { continue; } if (super.isSelectedIndexSelected(i)) { return false; } } return true; } }
To use this ListSelectionModel, you can set it to the JTable using the setSelectionModel method:
JTable table = new JTable(data, columnNames); table.setSelectionModel(new NonContinuousSelectionModel());
This approach allows for greater customization and control over the cell selection process, enabling complex selection scenarios that may not be supported by the default JTable behavior.
The above is the detailed content of How to achieve non-continuous cell selection in a JTable?. For more information, please follow other related articles on the PHP Chinese website!