Hi Alfie,
Not sure about the StackOverflowError without seeing the code and understanding what sort of component you are painting, but with regards to Sheriff Ritchie's answer, paintComponent is the correct method for all your painting code to be placed into when using lightweight Swing components. It's not really an 'advantage' thing. It's a 'proper way' thing.
The correct signature for paintComponent() is:
(@Override is optional, but a good idea when overriding. It helps insure you are overriding the intended method signature)
The reason you call the super's paintComponent method in the first line is to clear the existing graphics from the component - effectively, the super's paintComponent erases any existing graphics in the component and gives your custom code a clean piece of paper to draw on.
So, what does the paint() method do? It invokes several methods in the following order:
1) paintComponent()
2) paintBorder()
3) paintChildren()
Now, normally you don't ever call paint() directly. Instead you would call repaint() - which will suggest to the JVM that the component should be repainted when resources are available.
If I remember correctly (before my time with
Java, but I'm sure some of the more senior folks can correct me), AWT (the precursor to Swing) had only a paint() method to draw heavyweight components. When Swing was introduced, and extended from AWT heavyweight components, paint() was retasked to call the methods I've outlined above in lightweight Swing components.
I found this old article that should help explain in detail if you are curious:
http://www.oracle.com/technetwork/java/painting-140037.html
Cheers!
Chris