调用JPanel.getGraphics()出现java.lang.NullPointerException

qinguan0619 2011-12-15 10:28:36
各位大大,我想画个网格,但是
Graphics graphics = panel.getGraphics();
这条语句却报出java.lang.NullPointerException?
不知什么原因,求解,谢谢.


package test;

import java.awt.*;
import javax.swing.*;

public class TestGrid extends JFrame{

public static void main(String[] args) {
TestGrid game = new TestGrid();
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setVisible(true);
}

public TestGrid(){
super();
this.setTitle("just a test!");
this.setSize(600, 400);
this.getContentPane().setLayout(new BorderLayout());

DrawGrid(resultPanel);
this.add(resultPanel,BorderLayout.CENTER);
}


private void DrawGrid(JPanel panel) {
width = panel.getWidth();
height = panel.getHeight();

section_width = width / 20;
section_height = height / 20;

remainder_width = width - section_width * 20;
remainder_height = height - section_height * 20;

Graphics graphics = panel.getGraphics();
graphics.clearRect(0, 0, width, height);

for (int i = 0; i <= 20; i++) {
graphics.drawLine(remainder_width / 2 + section_width * i,
remainder_height / 2,
remainder_width / 2 + section_width * i,
height - remainder_height / 2);
}

for (int i = 0; i <= 20; i++) {
graphics.drawLine(remainder_width / 2,
remainder_height / 2 + section_height * i,
width - remainder_width / 2,
remainder_height / 2 + section_height * i);
}
}

private int width ;
private int height ;
private int section_width;
private int section_height;
private int remainder_width;
private int remainder_height;
private JPanel resultPanel = new JPanel();
}


...全文
271 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yonghenghu1 2013-06-08
  • 打赏
  • 举报
回复
控件的运行机制是,如果你在控件刚初始化的时候,就要调用getGr方法,那么不如直接重写paint方法,在控件在容器中显示后,在想修改显示内容就可以调用getGr方法,重写绘制图形了
huntor 2011-12-16
  • 打赏
  • 举报
回复
This method will return null if this component is currently not displayable.
qinguan0619 2011-12-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 huangjinjin520 的回复:]

这句好里的graphics为空啊~~没取到
graphics.clearRect(0, 0, width, height);
[/Quote]

这个为什么会没取到的?很纳闷,一直没搞明白。
wang7535067 2011-12-15
  • 打赏
  • 举报
回复
同意 楼上,
BUG弄潮儿 2011-12-15
  • 打赏
  • 举报
回复
这句好里的graphics为空啊~~没取到
graphics.clearRect(0, 0, width, height);

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧