Java如何以及何时精确调用paint()方法? [英] Java how and when exactly is the paint() method called?

查看:1200
本文介绍了Java如何以及何时精确调用paint()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多次我被告知,当我将类扩展到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中为该类创建一个对象,但是我得到了NullPointerException

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.

这篇关于Java如何以及何时精确调用paint()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆