java paint方法调用,Java如何以及何时精确调用paint()方法?

博客讨论了在Java Swing中进行自定义绘图时遇到的问题,即`paint()`方法未被调用导致无法绘制矩形。原因是创建并扩展的`JFrame`实例没有设置为可见,而创建的另一个`JFrame`实例没有自定义绘图。解决方案是通过重写`JPanel`的`paintComponent()`方法进行定制绘画,并将该面板添加到帧中。博客建议参考Swing教程的自定义绘画部分以获取正确的方法和示例。
摘要由CSDN通过智能技术生成

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:

You extend a JFrame and override the paint() method, but that frame is never made visible so the paint() method is never invoked.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值