configure Stop Cell Editing for JTable - Java Swing

Java examples for Swing:JTable Cell

Description

configure Stop 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 configureStopCellEditing(final JTable table,
            AbstractButton... buttons) {
        for (AbstractButton button : buttons) {
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    stopCellEditing(table);
                }/*from   w  ww.j  a  v a  2  s.  c  o m*/
            });
        }
    }

    public static void stopCellEditing(JTable table) {
        if (table.isEditing()) {
            int[] selection = table.getSelectedRows();
            table.getCellEditor().stopCellEditing();
            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