Stefan Stanković Stefan Stanković - 2 months ago 11
Java Question

Can I call getGraphics() inside overridden paint(Graphics)?

I'm using lambda functions with custom functional interfaces to shorten some nested loops that occur regularly in my code. As I don't want to add additional parameters to my expressions and end with something like this all over my code:

doubleLoop((int i, int j, Graphics graphics) -> drawHexagonRandomColor(i, j, graphics), g);


can I call
getGraphics()
to get the graphics context inside my
@Override public void paint(Graphics g) {...}
(instead of using the parameter
g
) without unexpected/negative side-effects?

Answer

can I call getGraphics() inside my @Override public void paint(Graphics g) {...} without unexpected/negative side-effects?

What's the point? paint already has a reference to Graphics.

What happens when someone else wants to use your code? Will they know NOT to call these methods outside of the context of the paint routine?

Are there consequences? Not the way you're intending to use it, but what happens if you want to change to using a BufferedStrategy instead of the standard painting routine? What happens if you want to paint the results to a BufferedImage instead?

You've build in an inflexible solution which has it's own dangerous side effects. For the preserved benefit (of not having one additional parameter), you lose a lot of flexibility, reuse and self documentation.

No one else will use my code

That's only part of the point, you should always challenge yourself to assume that someone else will use your code, it makes you a better developer, stops you from taking shortcuts or cutting corners.

getGraphics is just a bad idea generally and should be avoided wherever possible