The task is to enable users to select multiple non-contiguous cells in a JTable, allowing for more flexible cell selection beyond groups of continuous cells.
1. Utilizing ListSelectionModel
The JTable's setSelectionModel() method allows you to customize the selection model. By setting it to ListSelectionModel.SINGLE_SELECTION and adding a listener to handle InputEvent.CTRL_MASK, you can implement non-continuous cell selection.
2. Customizing MouseEvent Processing
By overriding the processMouseEvent() method in the JTable, you can modify the event's modifiers to indicate that the control key is pressed. This way, the table will behave as if the user is holding down the control key, enabling multiple cell selection.
3. Implementing a Custom List Selection Model
If the built-in selection models don't meet your requirements, you can create your own ListSelectionModel implementation that manages cell selection in the desired manner.
4. Example Implementation
The following code snippet provides an SSCCE that demonstrates the custom processMouseEvent() approach for allowing non-continuous cell selection in a JTable:
import java.awt.Component; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import javax.swing.*; public class TableSelection extends JFrame { public TableSelection() { JPanel main = new JPanel(); // Initialize table data String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"}; Object[][] data = { {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)}, {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)}, {"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)}, {"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)}, {"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)} }; // Override processMouseEvent to add control modifier JTable table = new JTable(data, columnNames) { @Override protected void processMouseEvent(MouseEvent e) { int modifiers = e.getModifiers() | InputEvent.CTRL_MASK; MouseEvent myME = new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), modifiers, e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), e.getButton()); super.processMouseEvent(myME); } }; JScrollPane pane = new JScrollPane(table); main.add(pane); this.add(main); } public static void main(String[] args) { new TableSelection(); } }
This implementation allows you to select non-contiguous cells by holding down the control key while clicking on the desired cells.
The above is the detailed content of How to Allow Non-Continuous Cell Selection in a JTable?. For more information, please follow other related articles on the PHP Chinese website!