Java Can';不要使用加载的字体
我的代码没有什么问题。加载变量“font”时无法使用它Java Can';不要使用加载的字体,java,fonts,compiler-errors,try-catch,jbutton,Java,Fonts,Compiler Errors,Try Catch,Jbutton,我的代码没有什么问题。加载变量“font”时无法使用它 try{ font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(new File("Font/M2c Light.ttf"))).deriveFont(Font.PLAIN,24); }catch(Exception ex){ ex.printStackTrace(); } 当我想在按钮上使用它时 Button.setFont(font
try{
font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(new File("Font/M2c Light.ttf"))).deriveFont(Font.PLAIN,24);
}catch(Exception ex){
ex.printStackTrace();
}
当我想在按钮上使用它时
Button.setFont(font);
这个错误告诉我:
variable font might not have been initialized
试试这个代码。让我知道它是否有效
try {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
//Handle exception
}
您没有搜索错误吗?请执行以下操作:
Font=null
或选择一些默认的Font
,而不是使用null
。(错误的原因是,由于对font
的赋值在try
块中,因此不能保证font
会有值。)您也可以将font=null
(或者更好的是,一些默认的font
)放在catch
块中。