您当前的位置: 首页 >  Java

星拱北辰

暂无认证

  • 1浏览

    0关注

    1205博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Java】panel.getGraphics()报错空指针异常的解决方法

星拱北辰 发布时间:2022-08-13 20:30:32 ,浏览量:1

如下的Swing代码:

public class GraphicsNullPointerDemo {

    public static void main(String[] args) {
        JFrame frame = new JFrame("空指针异常");
        frame.setLayout(new FlowLayout());
        frame.setSize(400, 200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        frame.add(panel, BorderLayout.CENTER);
        System.out.println(panel.getGraphics());
        frame.setVisible(true);
    }

}

输出的panel.getGraphics()值是null

反之,调换frame.setVisible(true)panel.getGraphics()的顺序,则不会为null

事实上,getGraphics()经常有空指针异常的可能性,所谓"This method will return null if this component is currently not displayable.",因此应该先setVisible(true)getGraphics()

关注
打赏
1660750074
查看更多评论
立即登录/注册

微信扫码登录

0.0524s