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