700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 【Java】panel.getGraphics()报错空指针异常的解决方法

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

时间:2020-10-21 11:59:45

相关推荐

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

如下的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()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。