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

2022-01-24 00:00:00 java swing paint jframe

我被告知很多次,当我将我的类扩展到 JFrame 时,paint() 方法将在需要时被调用,但例如.在代码中,paint 方法没有被调用,我没有看到任何矩形绘制.

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.

我什至尝试在构造函数(我创建的)中调用paint方法,然后为main中的类创建一个对象,但我得到了一个N​​ullPointerException

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. 您扩展了一个 JFrame 并覆盖了 paint() 方法,但该框架永远不会可见,因此永远不会调用 paint() 方法.

  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 并使其可见,但该框架没有自定义绘画,因此您只能看到该框架.

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

无论如何,这不是进行自定义绘画的方式.自定义绘画是通过覆盖 JPanel 的 paintCompnent(...) 来完成的,然后将面板添加到框架中.阅读 自定义绘画 上的 Swing 教程部分了解更多信息您可以自定义的信息和工作示例.

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.

本教程示例将向您展示创建类的更好方法,因此无需扩展 JFrame.按照教程示例进行操作.

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.

相关文章