xtrinch
xtrinch

Reputation: 2281

Re-painting of JPanel on hover/click of a JMenuItem

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.

Upvotes: 1

Views: 115

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168815

… (my overridden paintComponent is being called) when I hover or click on my JMenuitems. That is a problem, … Why is this …

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 …

… on the JPanel are programmatically constructed images (randomly seeded), and the construction takes a while, …

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.

Upvotes: 3

Related Questions