简体   繁体   English

谁在我的类中调用paintComponent()方法?

[英]Who is calling the paintComponent() method in my class?

I have a simple class that paints a graphic in a JPanel. 我有一个简单的类在JPanel中绘制图形。 This is my class: 这是我的班级:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;

class Drawing_panel extends JPanel {
    public void paintComponent(Graphics g) {
    super.paintComponent(g);       
    this.setBackground(Color.white);
    g.setColor(Color.red);
    g.fillRect(150, 80, 20, 20);
}  

public Dimension getPreferredSize(){
    return new Dimension(500,500);
}

} }

I have another class that instantiates this one: 我有另一个实例化这个的类:

Drawing_panel dp = new Drawing_panel();

There is no constructor in the Drawing_panel class and/or no explicit call to either the paintComponent() or getPreferredSize() methods. Drawing_panel类中没有构造函数和/或没有对paintComponent()getPreferredSize()方法的显式调用。 I assume the method is being called in the parent JPanel constructor, but I did not see the calls there either. 我假设在父JPanel构造函数中调用该方法,但我也没有看到它的调用。

The paintComponent is called from a few different places. paintComponent是从几个不同的地方调用的。 The call from JComponent.paint is probably the one you're looking for. 来自JComponent.paint的调用可能是您正在寻找的调用。

Note that paintComponent is not called from any constructor . 请注意, 不会从任何构造函数中调用 paintComponent The paintComponent is called "on-demand" ie when the system decides that the component needs to be redrawn. paintComponent被称为“按需”,即系统决定需要重新绘制组件时。 (Could for instance be when the component is resized, or when the window is restored from a minimized state.) To be clear: The component is not "painted, then used", it is "used, then painted when needed". (例如,可以在调整组件大小时,或者从最小化状态恢复窗口时。)要清楚:组件不是“涂漆,然后使用”,它是“使用,然后在需要时涂漆”。

This whole chain of painting-calls is nothing you should bother about, as it is taken care of entirely by the Swing and the so called Event Dispatch Thread. 整个绘画调用链都不是你应该打扰的,因为它完全由Swing和所谓的Event Dispatch Thread完成。

When you subclass JComponent or JPanel to draw graphics, override the paintComponent() method. 将JComponent或JPanel子类化为绘制图形时,请覆盖paintComponent()方法。 This method is called because the user did something with the user interface that required redrawing, or your code has explicitly requested that it be redrawn. 调用此方法是因为用户使用需要重绘的用户界面执行了某些操作,或者您的代码已明确请求重绘它。 Called automatically when it becomes visible When a window becomes visible (uncovered or deminimized) or is resized, the "system" automatically calls the paintComponent() method for all areas of the screen that have to be redrawn. 当它变得可见时自动调用当窗口变得可见(未覆盖或最小化)或调整大小时,“系统”会自动调用paintComponent()方法,以获取必须重新绘制的所有屏幕区域。

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

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