add JTable Model Tracker - Java Swing

Java examples for Swing:JTable Model

Description

add JTable Model Tracker

Demo Code

/*//from  w  w  w.j ava 2 s. com
 * Copyright 2015 Matthew Aguirre
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JTable;

import javax.swing.event.TableModelListener;

import javax.swing.table.TableModel;

public class Main {
    public static PropertyChangeListener addModelTracker(JTable p_Table,
            final TableModelListener p_Listener) {
        PropertyChangeListener propListener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent event) {
                TableModel oldModel = (TableModel) event.getOldValue();
                TableModel newModel = (TableModel) event.getNewValue();
                if (oldModel != null) {
                    oldModel.removeTableModelListener(p_Listener);
                }
                if (newModel != null) {
                    newModel.addTableModelListener(p_Listener);
                }
            }
        };
        p_Table.addPropertyChangeListener("model", propListener);
        p_Table.getModel().addTableModelListener(p_Listener);
        return propListener;
    }
}

Related Tutorials