Java how and when exactly is the paint() method called?(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);
}
}
推荐答案
你有两个框架:
您扩展了一个 JFrame 并覆盖了 paint() 方法,但该框架永远不会可见,因此永远不会调用 paint() 方法.
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() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 如何以及何时调用paint() 方法?


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01