Home >Java >javaTutorial >How to Synchronize Multiple Row Checkbox Selections in a JTable?

How to Synchronize Multiple Row Checkbox Selections in a JTable?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 17:10:15191browse

How to Synchronize Multiple Row Checkbox Selections in a JTable?

Multiple Row Selection in JTable

When confronted with a JTable containing non-editable text and boolean checkboxes, it is desirable to uncheck all boxes under selection when any one of them is unchecked, and vice versa.

To facilitate this behavior, consider the example below:

import java.awt...;
import javax.swing...;

public class CheckABunch extends JPanel {
    // Constants and variables for data model and JTable setup
    private static final int CHECK_COL = 1;
    private static final Object[][] DATA = {...};
    private static final String[] COLUMNS = {...};
    private DataModel dataModel = ...;
    private JTable table = ...;
    private DefaultListSelectionModel selectionModel;

    // Constructor initializes the interface and selection model
    public CheckABunch() {
        super(new BorderLayout());
        ...
        table.setPreferredScrollableViewportSize(...);
        selectionModel = ...;
    }

    // DataModel provides custom column classes and editability
    private class DataModel extends DefaultTableModel {
        public DataModel(Object[][] data, Object[] columnNames) {...}
        public Class<?> getColumnClass(int columnIndex) {...}
        public boolean isCellEditable(int row, int column) {...}
    }

    // ControlPanel contains buttons for selecting and clearing
    private class ControlPanel extends JPanel {
        public ControlPanel() {...}
    }

    private class SelectionAction extends AbstractAction {
        boolean value;
        public SelectionAction(String name, boolean value) {...}
        public void actionPerformed(ActionEvent e) {...}
    }

    // Main method for creating and displaying the interface
    public static void main(String[] args) {...}
}

In this example, SelectionAction handles the button clicks to update the checkboxes based on the user's selection. The dataModel ensures that the checkbox column is editable and of the correct type.

By using this approach, you can easily implement multiple row checkbox selection and synchronization in your JTable.

The above is the detailed content of How to Synchronize Multiple Row Checkbox Selections 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