Java Can';不要使用加载的字体

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

我的代码没有什么问题。加载变量“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
块中。