jFrame GetGraphics is null in java While Drawing image

后端 未结 1 1866
遥遥无期
遥遥无期 2021-01-26 16:08

I\'m getting null exception error while drawing image to jframe. i debug the code and check the image and frame is not null but still it is throwing NULL exception while drawin

相关标签:
1条回答
  • 2021-01-26 16:11

    The NPE is likely coming from here:

    Graphics ga=jf.getGraphics();
    

    as per docs:

    Creates a graphics context for this component. This method will return null if this component is currently not displayable.

    1) Dont use Component#getGraphics as its bad pratice/not persistent and will return null unless component is visible.

    2) Rather use JPanel and override paintComponent(Graphics g) dont forget to call super.paintComponent(g); as first call in overriden paintComponent.

    3) Override getPreferredSize() and return correct Dimensions to fit image being drawn.

    4) add JPanel to the frame for image to be visible of course.

    Alternatively You could also use a JLabel which would require nothing more than a setIcon(..) call and be added added to JFrame.

    Here are some of my examples:

    Using JPanel:

    • Loading image in Java Code from C drive

    • Image Drawing Works for JFrame, But Not JPanel

    • How to display an image in a frame?

    • Convert a JPanel to an image in a JScrollPane

    Using JLabel:

    • Image resizing and displaying in a JPanel or a JLabel without loss of quality
    0 讨论(0)
提交回复
热议问题