Selecting Non-Continuous Cells in JTable
In JTable, the default selection mode allows only contiguous cell selection. To enable individual, non-continuous cell selection, the following approaches can be considered:
1. CTRL MOUSE_CLICK:
If setSelectionMode(ListSelectionModel.SINGLE_SELECTION) is not set, holding down the CTRL key while clicking on cells allows for multiple non-continuous cell selection.
2. Modified ListSelectionModel:
As ListSelectionModel is shared by both JTable and JList, the following modified ListSelectionModel can be used:
import java.awt.Component; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import javax.swing.*; public class NonContSelectionModel extends DefaultListSelectionModel { @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); } }
This model can be applied to JTable by using setSelectionModel(new NonContSelectionModel()).
Demonstration:
The following code snippet creates a JTable that allows for non-continuous cell selection using the modified ListSelectionModel:
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; public class NonContJTableSelection { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); String[] columnNames = {"Name", "Age", "Profession"}; Object[][] data = { {"John Doe", 30, "Software Engineer"}, {"Jane Doe", 28, "Doctor"}, {"Peter Jones", 45, "Lawyer"} }; JTable table = new JTable(data, columnNames); table.setSelectionModel(new NonContSelectionModel()); JScrollPane scrollPane = new JScrollPane(table); panel.add(scrollPane); frame.add(panel); frame.pack(); frame.setVisible(true); } }); } }
The above is the detailed content of How to Enable Non-Continuous Cell Selection in JTable?. For more information, please follow other related articles on the PHP Chinese website!