Search code examples
javaswingjpanelbufferedimagejmenu

JMenu leaves a gray box above a JPanel on which image is drawn


I am trying to create a menu for my program, which draws some geometric objects on a JPanel using .getGraphics().drawImage(..)

The problem I'm having is that after I select an item on this menu, the text disappears but the background color doesn't. The slection ivokes a method which redraws the image on this panel using the above command, but apparently it doesn't help in removing it.

After I click this menu item and this gray box is left after the menu, I can make it disappear by moving the scene around using my mouse, which basically calls the same method used after the menu item click. This confuses me as to why the menu item method call doesn't remove the box, but next call of this method does.

Any idea on why is this happening and/or how to fix it?

Thank you.

Picture (A, B are JMenus on JMenuBar and the gray box below is left after JRadioButtonMenuItem selection): A, B are JMenus on JMenuBar and the gray box below is left after JRadioButtonMenuItem selection


Solution

  • which draws some geometric objects on a JPanel using .getGraphics().drawImage(..)

    Don't use getGraphics() to do custom painting.

    Custom painting is done by overriding the paintComponent(...) method of the JPanel. And don't forget to invoke super.paintComponent(...) as the first statement.

    Read the section from the Swing tutorial on Custom Painting for more information and working examples.