I keep getting a compile error on the return menuFont line it says there is no variable menuFont. Could someone please tell how to fix this.
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class loadFiles {
Font getFont(){
try {
Font menuFont = Font.createFont( Font.TRUETYPE_FONT, new FileInputStream("font.ttf"));
} catch (FileNotFoundException e) {
System.out.println("Cant find file.");
e.printStackTrace();
} catch (FontFormatException e) {
System.out.println("Wrong file type.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Unknown error.");
e.printStackTrace();
}
return menuFont;
}
}
Place a return statement either in the exception handler, in a finally block, or after the exception handler. Show activity on this post. The error is that you are not returning anything in the case where an exception is thrown. Show activity on this post.
Variables declared within the try/catch block are not in scope in the containing block, for the same reason that all other variable declarations are local to the scope in which they occur: That's how the specification defines it. :-) (More below, including a reply to your comment.)
Variables declared inside a try or catch block are local to the scope of the block.
The basic problem with your code is that the Font object is only in scope for the duration of the try block, so it's no longer available in your return statement at the end of the method. Two options:
Move the variable declaration outside the try block:
Font menuFont = null;
try {
menuFont = Font.createFont(...);
}
catch (...) {
}
return menuFont;
Or, do return Font.creatFont(...)
inside the try, thus avoiding the need for the variable in the first place (and, obviously, return null
at the end of the method).
The menuFont
variable scope is inside the try block. Move the variable outside of it instead.
Something like:
Font getFont(){
Font menuFont = null;
try {
menuFont = Font.createFont( Font.TRUETYPE_FONT, new FileInputStream("font.ttf"));
} catch (FileNotFoundException e) {
System.out.println("Cant find file.");
e.printStackTrace();
} catch (FontFormatException e) {
System.out.println("Wrong file type.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Unknown error.");
e.printStackTrace();
}
return menuFont;
}
Be aware that in case of an exception, this method will return a null
font.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With