I am encountering some issue while trying to set font for drawing string function in Java.
My goal is to draw something on image using function drawString(text, posLeft, posTop);
where text
is the string, and posLeft
and posTop
are positions of it from left and top of the screen.
In that purpose i have following code:
Icon icon = new ImageIcon(image);
image.getGraphics().setFont(new Font("Arial", Font.BOLD, size));
image.getGraphics().setColor(c);
image.getGraphics().drawString(text, posLeft, posTop);
image.getGraphics().dispose();
where image
is instance of java.awt.BufferedImage
class object, icon
is instance of javax.swing.Icon
with constructor of class javax.swing.ImageIcon.ImageIcon(Image image)
. Font is of the class java.awt.Font
.
Then i'm getting graphics with image.getGraphics()
, however null pointer exception occurs while trying to set font part, in line image.getGraphics().setFont(new Font("Arial", Font.BOLD, size));
.
The error message is only java.lang.NullPointerException: null
. I tried changing font but it is still the same.
Would very appreciate any help regarding this!
(hope i didn't miss some important part)
Both image and image.getGraphics() are working, since i checked it in the code and got following:
BufferedImage@3c52b5ae: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@35069130 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 659 height = 587 #numDataElements 3 dataOff[0] = 2
----
sun.java2d.SunGraphics2D[font=java.awt.Font[family=Dialog,name=Dialog,style=plain,size=12],color=java.awt.Color[r=255,g=255,b=255]]
----
where first part above---
is image
, and later is image.getGraphics()
.
Also, I tried using Font f=new Font('Arial',Font.BOLD,size)
, and there i firstly got null pointer exception and some null value occurring there.