Friday, 15 May 2015

How to load font in java? -



How to load font in java? -

i want include font called fixedsys in game , code utilize :

try{ font myfont = null; file fontfile = new file("fixedsys.ttf"); if(fontfile.exists()){ myfont = font.createfont(font.truetype_font, fontfile).derivefont(font.plain, 22f); graphicsenvironment ge = graphicsenvironment.getlocalgraphicsenvironment(); ge.registerfont(myfont); system.out.println("not null"); }else{ system.out.println("file not exist"); } } grab (fontformatexception e) { // todo auto-generated grab block e.printstacktrace(); } grab (ioexception e) { // todo auto-generated grab block e.printstacktrace(); }

for reason, java thinks file not exist , prints out file not exist line. have searched through google , stackoverflow none of work when utilize :

mycomponent.setfont(myfont);

i error saying:

cannot find variable myfont

i have checked on , on , on nil seems wrong.

edit : removed if(file.exists()) line , different error. :

cannot read fixedsys.ttf !

edit 2 : ug_'s comment proved right. java looking in wrong folder file. thanks.

the myfont variable local variable within grab block , hence doesn't exist anywhere else.

you have create class variable utilize outside grab block.

like so:

class someclass { // declare here private font myfont; public someclass() { try{ // initialize here file fontfile = new file("fixedsys.ttf"); if(fontfile.exists()){ myfont = font.createfont(font.truetype_font, fontfile).derivefont(font.plain, 22f); graphicsenvironment ge = graphicsenvironment.getlocalgraphicsenvironment(); ge.registerfont(myfont); system.out.println("not null"); }else{ system.out.println("file not exist"); } } grab (fontformatexception e) { // todo auto-generated grab block e.printstacktrace(); } grab (ioexception e) { // todo auto-generated grab block e.printstacktrace(); } } // somewhere else: mycomponent.setfont(myfont); }

java

No comments:

Post a Comment