Home  >  Article  >  Java  >  How to achieve non-continuous cell selection in a JTable?

How to achieve non-continuous cell selection in a JTable?

Susan Sarandon
Susan SarandonOriginal
2024-11-09 01:13:02327browse

How to achieve non-continuous cell selection in a JTable?

Non-Continuous Cell Selection in JTable

Allowing users to select individual non-continuous cells in a JTable provides greater flexibility and user convenience. Here's how you can achieve this:

CTRL MOUSE_CLICK

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.

ListSelectionModel Implementation

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn