Search code examples
javaswingjtablecode-reuserowcount

JTable row totals color coded label


I have 5 JTables on different forms with arbitrary numbers of rows and I would like to have a label for each one that will show me the total number of rows in that table and also change color for 3 seconds when the row count changes. The color should go green if incrementing and red if decrementing. What would be the best way to implement this such that I do not need to duplicate too much code in each of my forms?


Solution

  • basically, you add a TableModelListener to the JTable's model and on receiving change events, update the corresponding labels as appropriate

    some code:

    public class TableModelRowStorage 
        // extends AbstractBean // this is a bean convenience lass  of several binding frameworks
                                // but simple to implement directly  
         implements TableModelListener {
    
        private int rowCount;
    
        public TableModelRowStorage(TableModel model) {
            model.addTableModelListener(this);
            this.rowCount = model.getRowCount();
        }
        @Override
        public void tableChanged(TableModelEvent e) {
            if (((TableModel) e.getSource()).getRowCount() != rowCount) {
                int old = rowCount;
                rowCount = ((TableModel) e.getSource()).getRowCount();
                doStuff(old, rowCount);
            }
    
        }
    
        protected void doStuff(int oldRowCount, int newRowCount) {
            // here goes what you want to do - all in pseudo-code
            // either directly configuring a label/start timer
            label.setText("RowCount: " + newRowCount);
            label.setForeground(newRowCount - oldRowCount > 0 ? Color.GREEN : Color.RED);
            timer.start();
    
            // or indirectly by firing a propertyChange
            firePropertyChange("rowCount", oldRowCount, newRowCount);
        }
    
    }