我可以在覆盖的 paint(Graphics) 中调用 getGraphics() 吗?

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

我使用带有自定义功能接口的 lambda 函数来缩短我的代码中经常出现的一些嵌套循环。因为我不想在我的表达式中添加额外的参数并在我的代码中以 this 之类的结尾:

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

我可以调用 getGraphics() 在我的 @Override public void paint(Graphics g) {...} 中获取图形上下文(而不是使用参数 g)而没有 unexpected/negative 副作用吗?

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

有什么意义? paint 已经引用了 Graphics

当其他人想要使用您的代码时会发生什么?他们会知道不要在绘制例程的上下文之外调用这些方法吗?

有后果吗?不是您打算使用它的方式,但是如果您想更改为使用 BufferedStrategy 而不是标准绘画例程会怎样?如果您想将结果绘制到 BufferedImage 会怎样?

您建立了一个不灵活的解决方案,它有其自身的危险副作用。为了保留的好处(没有一个额外的参数),你失去了很多灵活性、重用和自我文档。

No one else will use my code

这只是重点的一部分,您应该始终挑战自己,假设其他人会使用您的代码,这会让您成为更好的开发人员,阻止您走捷径或偷工减料。

getGraphics 通常只是一个坏主意,应尽可能避免