Home > Java > javaTutorial > How to Implement Linked Checkboxes in a JTable for Multiple Row Selection?

How to Implement Linked Checkboxes in a JTable for Multiple Row Selection?

DDD
Release: 2024-12-05 19:43:11
Original
310 people have browsed it

How to Implement Linked Checkboxes in a JTable for Multiple Row Selection?

Selecting Multiple Rows and Checking All Checkboxes

In a JTable, where one column comprises non-editable text while the other features checkbox controls for boolean values, a common requirement is to link the checkboxes. This entails that when multiple rows are selected and any checkbox is unchecked, all other selected checkboxes also become unchecked. Similarly, if a checkbox is checked, all selected checkboxes should follow suit.

Implementing the Linked Checkboxes

Implementing a DataModel Class:

  • Extend the DefaultTableModel class to create a custom DataModel with overridden methods:

    • getColumnClass(int columnIndex): Return the class type for the checkbox column (Boolean.class).
    • isCellEditable(int row, int column): Allow cell editing only in the checkbox column.

Creating a Control Panel with Buttons:

  • Add a control panel with buttons for clearing or checking all selected checkboxes.

Creating a SelectionAction Class:

  • Implement an action class to handle button events.
  • The constructor accepts a boolean value representing the desired action (clear or check).
  • The actionPerformed method iterates over selected rows and updates the checkbox values accordingly.

Sample Code:**

The following code snippet demonstrates the implementation:

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.DefaultListSelectionModel;
import javax.swing.table.DefaultTableModel;

public class MultipleRowSelection extends JPanel {

    private static final int CHECK_COL = 1;
    private static final Object[][] DATA = {
        {"One", Boolean.TRUE}, {"Two", Boolean.FALSE},
        {"Three", Boolean.TRUE}, {"Four", Boolean.FALSE},
        {"Five", Boolean.TRUE}, {"Six", Boolean.FALSE},
        {"Seven", Boolean.TRUE}, {"Eight", Boolean.FALSE},
        {"Nine", Boolean.TRUE}, {"Ten", Boolean.FALSE}};
    private static final String[] COLUMNS = {"Number", "CheckBox"};
    private DataModel dataModel = new DataModel(DATA, COLUMNS);
    private JTable table = new JTable(dataModel);
    private DefaultListSelectionModel selectionModel;

    public MultipleRowSelection() {
        super(new BorderLayout());
        this.add(new JScrollPane(table));
        this.add(new ControlPanel(), BorderLayout.SOUTH);
        table.setPreferredScrollableViewportSize(new Dimension(250, 175));
        selectionModel = (DefaultListSelectionModel) table.getSelectionModel();
    }

    private class DataModel extends DefaultTableModel {

        public DataModel(Object[][] data, Object[] columnNames) {
            super(data, columnNames);
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex == CHECK_COL) {
                return getValueAt(0, CHECK_COL).getClass();
            }
            return super.getColumnClass(columnIndex);
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == CHECK_COL;
        }
    }

    private class ControlPanel extends JPanel {

        public ControlPanel() {
            this.add(new JLabel("Selection:"));
            this.add(new JButton(new SelectionAction("Clear", false)));
            this.add(new JButton(new SelectionAction("Check", true)));
        }
    }

    private class SelectionAction extends AbstractAction {

        boolean value;

        public SelectionAction(String name, boolean value) {
            super(name);
            this.value = value;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < dataModel.getRowCount(); i++) {
                if (selectionModel.isSelectedIndex(i)) {
                    dataModel.setValueAt(value, i, CHECK_COL);
                }
            }
        }
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("MultipleRowSelection");
        frame.add(new MultipleRowSelection());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowUI();
            }
        });
    }
}
Copy after login

Conclusion

By implementing these classes and action listeners, it becomes possible to select multiple rows in a JTable and toggle the corresponding checkboxes collectively, enhancing the user experience and streamlining data manipulation.

The above is the detailed content of How to Implement Linked Checkboxes in a JTable for Multiple Row Selection?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template