Search code examples
javaswingjtableswingxswingutilities

JTable high cpu usage on updates when minimized


UPDATE: So I've found out what is causing this issue. When my Java window is minimized, my table is rendering every single row. Does anyone know how to prevent this?

I have a JXTable that is constantly updating, deleting, and adding row data every second. We're talking about modifying 10-20 rows every second on average.

Typically, the CPU usage runs between 5% and 10%. It can hit 15% when we're pounding the table with hundreds of updates a second.

However, we've noticed that when our Java window is minimized, whenever ANY update comes through, our CPU usage hits 25% each and every time. We setup a script to add a single row every 5 seconds and when that single row comes through, we're seeing CPU usage hit 25%.

The only explanation I can think of is the use of SwingUtilities.invokeAndWait(). I'm modifying the row data in a background thread and using invokeAndWait for the various fireTableDataChanged() methods.

I use invokeAndWait because I need to fire off my events in order. E.g, I delete some rows, call fireTableRowsDeleted(), then I add some rows and call fireTableRowsInserted().

Any ideas why my CPU usage hits 25% ONLY when table updates and my window is minimized?


Solution

  • In JXTable, this method is called whenever the model changes:

    protected void postprocessModelChange(TableModelEvent e) {
        if (forceRevalidate && filteredRowCountChanged) {
            resizeAndRepaint();
        }
        filteredRowCountChanged = false;
        forceRevalidate = false;
    }
    

    The resizeAndRepaint() call was what appears to be forcing every single row to be repainted when the window is minimized. Overriding as below seems to fix the issue:

    @Override
    protected void resizeAndRepaint()
    {
        JFrame window = (JFrame)  SwingUtilities.getAncestorOfClass(JFrame.class, this);
        if(window != null && window.getState() != JFrame.ICONIFIED)
        {
            super.resizeAndRepaint();
        }
    }