2

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?

4

1 回答 1

5

基本上,您将 TableModelListener 添加到 JTable 的模型中,并在接收到更改事件时,根据需要更新相应的标签

一些代码:

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);
    }

}
于 2012-08-28T16:23:05.663 回答