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

我怕爱的太早我们不能终老 提交于 2020-01-07 06:17:57

问题


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. in the code the paint method is not being called and I don't see any rectangle drawn.

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

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);
    }
}

回答1:


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.

  2. Then you create a new JFrame which you make visible, but this frame has no custom painting so you just see the frame.

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. Read the section from the Swing tutorial on Custom Painting for more information and working examples that you can customize.

The tutorial example will show you a better way to create your class so there is no need to extend a JFrame. Follow the tutorial example.



来源:https://stackoverflow.com/questions/44269435/java-how-and-when-exactly-is-the-paint-method-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!