java 绘制、重绘、paintComponent

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16875572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:14:07  来源:igfitidea点击:

Paint, repaint , paintComponent

javaswinguser-interface

提问by The Answer

excuse me i search a lot to find how those 3 functions (paint, repaint, paintComponent) interact between them but i have no idea. Can you explain me exactly when they are called ( because sometimes java call it without me asking him) what they do exactly and what is the difference between them. Thank you

对不起,我搜索了很多以找到这 3 个函数(paint、repaint、paintComponent)如何在它们之间交互,但我不知道。你能准确地解释我什么时候被调用(因为有时java会在我不问他的情况下调用它)他们究竟做了什么,他们之间有什么区别。谢谢

回答by scottysseus

I am not sure about "paint", but I can explain the relationship between repaint() and paintComponent().

我不确定“paint”,但我可以解释 repaint() 和paintComponent() 之间的关系。

In my limited experience with java, the paintComponent() method is a method in the JPanel class and is a member of "swing".

在我有限的java经验中,paintComponent()方法是JPanel类中的一个方法,是“swing”的成员。

The paintComponent() method handles all of the "painting". Essentially, it draws whatever you want into the JPanel usings a Graphic object.

PaintComponent() 方法处理所有的“绘画”。本质上,它使用 Graphic 对象将您想要的任何内容绘制到 JPanel 中。

repaint() is an inherited instance method for all JPanel objects. Calling [your_JPanel_object].repaint() calls the paintComponent() method.

repaint() 是所有 JPanel 对象的继承实例方法。调用 [your_JPanel_object].repaint() 调用paintComponent() 方法。

Every time you wish to change the appearance of your JPanel, you must call repaint().

每次您希望更改 JPanel 的外观时,都必须调用 repaint()。

Certain actions automatically call the repaint() method:

某些操作会自动调用 repaint() 方法:

  • Re-sizing your window
  • Minimizing and maximizing your window
  • 重新调整窗口大小
  • 最小化和最大化你的窗口

to name a few.

仅举几例。

IN SHORT paintComponent() is a method defined in JPanel or your own custom class that extends JPanel. repaint() is a method called in another class (such as JFrame) that eventually calls paintComponent().

简而言之,paintComponent() 是在 JPanel 或您自己的扩展 JPanel 的自定义类中定义的方法。repaint() 是在另一个类(如 JFrame)中调用的方法,它最终调用了paintComponent()。

here is an example:

这是一个例子:

    public class MyPanel extends JPanel{

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        g.draw([whatever you want]);

        ...
        ...

    }
}
public class MyFrame extends JFrame{

    public MyFrame(){

    MyPanel myPanel = new MyPanel();

    myPanel.repaint();

    }

}