简体   繁体   中英

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 ()). I was just curious to see if we can draw graphics outside the paintComponent. Is that even possible? is it possible to write a line in the main method like: fillRect(100,100, 500,400); and have it draw a rectangle? If it is possible, is it conventional according to Java?

Basically, I'm asking if you can draw graphics outside the paintComponent class and is it conventional.

You can draw to a BufferedImage , but if you want it drawn on the screen then generally, you'll need to use 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.

See Painting in AWT and Swing and Performing Custom Painting for more details

If you need more control over the paint process you could also use a BufferStrategy

See BufferStrategy and BufferCapabilities for more details

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. This is why you MUST perform your painting within the context of a paint cycle (ie - in the paintComponent method)
  • BufferStrategy uses a "active rendering" approach, which gives you complete control of the painting process, but it's not capable of painting Swing components

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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