This is caused by the basic fact that you have broken the paint
chain.
Painting in AWT/Swing is made of a chain of method calls. If you neglect to maintain this chain, you start ending up with paint artifacts, in the form you are seeing.
The Graphics
context is a shared resource, that is, every component painted during any given paint cycle will be given the same Graphics
resource. Each component is expected to prepare the Graphics
context before painting to it…
To fix the problem, in all your paint
methods, you should be calling super.paint(g)
to ensure that the paint chain is maintained and that the Graphics
context is preapred for the individual components painting needs.
Having said that. It is not recommended to override paint
of top level containers. Instead, it is recommended that you perform your custom painting using something like a JPanel
and override it’s paintComponent
method instead (ensuring that you call super.paintComponent
as well!)
This has a least two basic benefits. The first is, you can know decide where the panel should be displayed, for example, you could add it to an JApplet
or JFrame
or other container as you see fit. It is double buffered by default. This means you won’t see any flicker when the painting is updated.
You should consider breaking your application down into small panels, focusing on each of the components needs separately. This will help reduce the complexity of your application and make it easier to manage the individual needs of each section of your application.
Take a look at Performing Custom Painting and Painting in AWT and Swing for more details
4
solved Java Hangman GUI not properly displaying [closed]