简体   繁体   English

paintComponent()外部的图形形状(java)

[英]Drawing Shapes outside paintComponent() (java)

I'm new to graphics in java and am having difficulty grasping the whole concept of drawing all your graphics from one method (paintComponent ()). 我对Java中的图形是陌生的,并且难以掌握从一种方法(paintComponent())绘制所有图形的整个概念。 I was just curious to see if we can draw graphics outside the paintComponent. 我只是想知道我们是否可以在paintComponent之外绘制图形。 Is that even possible? 那有可能吗? is it possible to write a line in the main method like: fillRect(100,100, 500,400); 是否可以在main方法中编写一行,例如:fillRect(100,100,500,400); and have it draw a rectangle? 并绘制一个矩形? If it is possible, is it conventional according to Java? 如果可能的话,这是Java的传统做法吗?

Basically, I'm asking if you can draw graphics outside the paintComponent class and is it conventional. 基本上,我在问您是否可以在paintComponent类之外绘制图形,这是否是常规的。

You can draw to a BufferedImage , but if you want it drawn on the screen then generally, you'll need to use paintComponent . 您可以绘制到BufferedImage ,但是如果要在屏幕上绘制,则通常需要使用paintComponent You can pass the instance of Graphics which is passed into paintComponent to other classes which can do more complex operations, but you should never maintain a reference that instance or try painting outside of a paint cycle context. 您可以将传递给paintComponentGraphics实例传递给其他类,这些类可以执行更复杂的操作,但是您永远不要维护该实例的引用或尝试在绘制循环上下文之外进行绘制。

See Painting in AWT and Swing and Performing Custom Painting for more details 有关更多详细信息,请参见“ AWT中的绘画”和“摇摆执行自定义绘画

If you need more control over the paint process you could also use a BufferStrategy 如果您需要对绘制过程进行更多控制,则还可以使用BufferStrategy

See BufferStrategy and BufferCapabilities for more details 有关更多详细信息,请参见BufferStrategy和BufferCapabilities

Things you should know: 您应该知道的事情:

  • Swing uses a "passive rendering" approach, this means that painting occurs when the paint system decides it needs to be done. Swing使用“被动渲染”方法,这意味着绘画是在绘画系统确定需要完成时进行的。 This is why you MUST perform your painting within the context of a paint cycle (ie - in the paintComponent method) 这就是为什么必须在绘制循环的上下文中执行绘制的原因(即-在paintComponent方法中)
  • BufferStrategy uses a "active rendering" approach, which gives you complete control of the painting process, but it's not capable of painting Swing components BufferStrategy使用“主动渲染”方法,可以完全控制绘画过程,但不能绘画Swing组件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM