当前位置: 代码迷 >> J2SE >> 调用JPanel.getGraphics()出现java.lang.NullPointerException解决办法
  详细解决方案

调用JPanel.getGraphics()出现java.lang.NullPointerException解决办法

热度:340   发布时间:2016-04-24 02:13:51.0
调用JPanel.getGraphics()出现java.lang.NullPointerException
各位大大,我想画个网格,但是
Graphics graphics = panel.getGraphics();
这条语句却报出java.lang.NullPointerException
不知什么原因,求解,谢谢.

Java code
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();}


------解决方案--------------------
这句好里的graphics为空啊~~没取到
graphics.clearRect(0, 0, width, height);

------解决方案--------------------
同意 楼上,
------解决方案--------------------
This method will return null if this component is currently not displayable.
  相关解决方案