How does paint () work without calling in the main method?

This is a beginner's question for java graphics using the awt package. I found this code on the Internet to draw simple graphics.

import java.awt.*; public class SimpleGraphics extends Canvas{ /** * @param args */ public static void main(String[] args) { SimpleGraphics c = new SimpleGraphics(); c.setBackground(Color.white); c.setSize(250, 250); Frame f = new Frame(); f.add(c); f.setLayout(new FlowLayout()); f.setSize(350,350); f.setVisible(true); } public void paint(Graphics g){ g.setColor(Color.blue); g.drawLine(30, 30, 80, 80); g.drawRect(20, 150, 100, 100); g.fillRect(20, 150, 100, 100); g.fillOval(150, 20, 100, 100); } } 

Nowhere in the main method is paint () called on the canvas. But I ran the program and it works, so how does the paint () method work?

+6
source share
3 answers

The paint method is called by the Thread Event Dispatch Thread (EDT) and basically gets out of your control.

It works as follows: when you implement the user interface (calling setVisible(true) in your case), Swing launches EDT. This EDT stream then runs in the background, and when your component needs to be painted, it calls the paint method with the appropriate Graphics instance, which you can use to draw.

So, when do you need to repaint a component? - For example, if

  • Window resizing
  • The component becomes visible.
  • When you call repaint
  • ...

Just assume that it will be called when necessary.

+12
source

In fact, you never call a mathode. It is automatically called automatically when you need to repaint the content area of ​​your frame. This happens when your frame is rendered for the first time, changes, maximizes (after the minimum), etc.

+5
source

If you do not know how the AWT / Swing drawing API (render) works, read this article - Painting in AWT and Swing .

Paint Method Regardless of how the paint request is triggered, AWT uses a "callback" mechanism for drawing, and this mechanism is the same for heavy and light components. This means that the program must place the component's rendering code inside a special overridden method, and this toolkit will call this method when it is time to draw. The method to be overridden is in java.awt.Component.

+3
source

Source: https://habr.com/ru/post/899277/


All Articles