Title: Re-painting of JPanel on hover/click of a JMenuItem
Tags: java;swing;jpanel;repaint;jmenuitem
Question: My desktop Java application has a JMenubar with several JMenuitems, and underneath it is a JPanel which I re-render when an item in the dropdown menu is clicked.
It all works okay, but my JPanel is re-rendering (my overridden paintComponent is being called) when I hover or click on my JMenuitems.
That is a problem, because on the JPanel are programmatically constructed images (randomly seeded), and the construction takes a while, so my program hangs if i hover over the menu too much..
Why is this and how do I fix it?
Edit: Even if I seed the random values and get the same image, the program does too many unecessary calculations and it becomes slow.

Here is the accepted answer: &#8230; (my overridden paintComponent is being called) when I hover or click on my JMenuitems. That is a problem, &#8230; Why is this &#8230;
It is expected behavior. The toolkit will repaint a panel whenever it determines it is necessary to do so:  E.G.s
A menu appearing or disappearing over it
Another window or dialog dis/appearing over it
The user resizing the window &#8230;
&#8230; on the JPanel are programmatically constructed images (randomly seeded), and the construction takes a while, &#8230;
To avoid having to recreate a complex paint, draw the details to a BufferedImage then either paint the image in the paint method, or (simpler) display it in a label.
Comment for this answer: Thank you, made it work as desired with BufferedImage.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:06/27/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><swing><jpanel><repaint><jmenuitem>', 'Title': 'Re-painting of JPanel on hover/click of a JMenuItem', 'ViewCount': 101, 'id': 31091977, 'user_AboutMe': '<p>I am a student of computer science, always eager to learn new things and expand my horizons.</p>\n', 'user_AccountId': 2793088.0, 'user_DisplayName': 'xtrinch', 'user_Reputation': 2192.0, 'user_Views': 242.0, 'user_id': 2402929.0}}