Search code examples
javaswingopacityjcomponentmouselistener

Java Swing - Change JComponent opacity from mouse listener


Pretty much like the title says - I've got a JPanel, and I'd like to have it at 90% opacity if inactive, and full opacity if moused over.

I've got the separate components working - the mouse over and out is OK and I can change the opacity from overriding the paintComponent method, but I suppose I'm having trouble with the connection between the MouseAdapter and the paintComponent.

It seems there's probably a really easy way to do this - any tips?

(BTW sorry left the code at home so no example for now :( unless it's not quickly solvable then I'll throw some code up tomorrow.)


Solution

  • If you are overriding the paintComponent method, you should be able to add an opacity variable to the JPanel extension. Modify this in the MouseAdapter (using mutators). Then refer to this variable in the overridden paintComponent method to determine how to paint.