简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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