Font class reference in java
I'd like to ask something very fundamental:
While I was writing this code:
font = new Font("Calibri", Font.ITALIC, 10);
gr.setFont(font);
gr.drawString("mpla mpla",x,y);
font = new Font("Sherif", Font.BOLD, 16);
gr.drawString("mpla mpla part 2",x,y);
I realised that my font wouldn't change in the second draws开发者_StackOverflow中文版tring and in order
to work I had to put another gr.setFont(font);
before it.
Why is this happening? I mean, I've got a reference for a Font
object, and that is set for use on my Graphics context. When I re-assign a new object to my font reference it should normally work when Graphics
tries to use it for the second time! but this is not the case..
Thanks in advance
You seem to have a misconception of what you're doing.
At this line:
font = new Font("Calibri", Font.ITALIC, 10);
You assign a reference to a newly created Font
object to the variable font
.
Then, using gr.setFont(font);
you pass that reference to the gr.setFont()
method. You pass only the reference, i.e. the "position" of that Font
object. You don't tell gr.setFont()
anything about the variable font
, you only tell it the value stored in there.
In the second-to-last line font = ...
you assign the reference to yet another new Font
object to the variable font
. Since the Graphics
object has no knowledge of the font
variable itself, it is (of course) not influenced by that change at all!
You could think of it that way:
- I write a number on a piece of paper (let's say the number is 3)
- I show you that piece of paper and ask you to remember the number
- I erase the number on the paper and write 5 on it
- I ask you which number you remembered
Yes you are right if gr will use the font which was passed in first call, at least it should (Ideally Class of gr should have defensively copied the font object and not used the same object what you used to set), in other case if implementation has not done that then whenever you change 'font' reference that you passed in setFont will change the font will change.
So if it works without use of second 'setFont()' call implementation of Graphic class has not done defensive copy. As far as 'what is happening' is concerned, it all depends whether Graphic class directly use this 'font' reference to store or it creates a copy and then store.
精彩评论