简体   繁体   English

Java如何以及何时精确调用paint()方法?

[英]Java how and when exactly is the paint() method called?

I have been told many times that the paint() method will be called as and when required when I extend my class to JFrame but for eg. 我被告知很多次,当我将类扩展到JFrame时(例如),将在需要时调用paint()方法。 in the code the paint method is not being called and I don't see any rectangle drawn. 在代码中,paint方法没有被调用,我看不到任何矩形绘制。

I even tried to call paint method inside the constructor (which I created) and then creating an obejct for the class in main but I got a NullPointerException 我什至尝试在构造函数(我创建的)中调用paint方法,然后在main中为该类创建一个对象,但得到了NullPointerException

import java.awt.Graphics;
import javax.swing.JFrame;

public class MyFirstDrawing extends JFrame
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public static void main(String args[])
    {
        JFrame w = new JFrame("Hello World");
        w.setTitle("My First Drawing");
        w.setDefaultCloseOperation(EXIT_ON_CLOSE);
        w.setSize(500,500);
        w.setVisible(true);
    }
    public void paint(Graphics g)
    {
        g.drawRect(40, 40, 100, 200);
    }
}

You have two frames: 您有两个框架:

  1. You extend a JFrame and override the paint() method, but that frame is never made visible so the paint() method is never invoked. 您扩展了一个JFrame并覆盖了paint()方法,但是该框架永远不可见,因此从来没有调用paint()方法。

  2. Then you create a new JFrame which you make visible, but this frame has no custom painting so you just see the frame. 然后创建一个新的JFrame,使它可见,但是此框架没有自定义绘画,因此您只能看到该框架。

In any case this is NOT the way to do custom painting. 无论如何,这不是定制绘画的方法。 Custom painting is done by overriding paintCompnent(...) of a JPanel and then you add the panel to the frame. 通过覆盖paintCompnent(...)来完成自定义绘制,然后将面板添加到框架中。 Read the section from the Swing tutorial on Custom Painting for more information and working examples that you can customize. 阅读有关定制绘画的Swing教程中的部分,以获取更多信息和可以定制的工作示例。

The tutorial example will show you a better way to create your class so there is no need to extend a JFrame. 本教程示例将向您展示一种创建类的更好方法,因此无需扩展JFrame。 Follow the tutorial example. 按照教程示例进行操作。

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

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