configure Cancel Cell Editing for JTable - Java Swing

Java examples for Swing:JTable Cell

Description

configure Cancel Cell Editing for JTable

Demo Code


//package com.java2s;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractButton;
import javax.swing.JTable;

public class Main {
    public static void configureCancelCellEditing(final JTable table,
            AbstractButton... buttons) {
        for (AbstractButton button : buttons) {
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    cancelCellEditing(table);
                }/* w  w w .j a v a 2s  . c o m*/
            });
        }
    }

    public static void cancelCellEditing(JTable table) {
        if (table.isEditing()) {
            int[] selection = table.getSelectedRows();
            table.getCellEditor().cancelCellEditing();
            if (selection.length > 0) {
                selectRows(table, selection);
            }
        }
    }

    public static void selectRows(JTable table, int[] rowIndexes) {
        table.getSelectionModel().setValueIsAdjusting(true);
        try {
            table.clearSelection();
            for (int row : rowIndexes) {
                table.addRowSelectionInterval(row, row);
            }
            if (table.getCellSelectionEnabled()) {
                table.setColumnSelectionInterval(0,
                        table.getColumnCount() - 1);
            }
        } finally {
            table.getSelectionModel().setValueIsAdjusting(false);
        }
    }
}

Related Tutorials