Skip to Main Content

Java SE (Java Platform, Standard Edition)


For appeals, questions and feedback, please email

Why is swing's getGraphics() so slow?

Tom SchepersMar 8 2024


I'm currently working with Swing, and I want to create some custom widgets with mouse hover effects.

I created a superclass of a JComponent and wrote a custom paintComponent and two methods for mouseEntered and mouseExited that change the background color.

When I store the background color in the built-in field using setBackground(), then paintComponent automatically gets called and perfectly draws the thing.

But then, I wanted to write seperate functions for drawing the background and drawing other stuff. So, I wrote a function drawBackground and let paintComponent call that function. And now, when mouseEntered or mouseExited is called, it should only change the background color (I created my own field currentBg for this) and then call drawBackground instead of paintComponent. And I need to have some Graphics2D I can draw the thing on, so I used getGraphics() and passed it to drawBackground.

But somehow, this way is much slower than the other one. It seems like getGraphics() just takes too much time. So, what would be a faster way to re-draw the element? In my first example, the thing gets re-drawn by the setBackground method, because it automatically updates the button and calls paintComponent. But I also tried changing my second example to make it call paintComponent instead of drawBackground, but that didn't change anything.

Somehow, calling paintComponent(getGraphics()) is much slower than the way setBackground updates the Component. So, what would be the best way to update the Component manually?

Thank you for answers!

Post Details
Added on Mar 8 2024