Setting a custom font to a JLabel - java

I'm doing a simple Pong game and wanted to add an 8-Bit font but can not figure how.
This is the method I used for JLabels:
public void drawScore()
{
player1 = "Player 1";
player2 = "Player 2";
JLabel leftScore = new JLabel(player1);
JLabel rightScore = new JLabel(player2);
leftScore.setForeground(Color.white);
rightScore.setForeground(Color.white);
leftScore.setLocation(20, 0);
rightScore.setLocation(730, 0);
leftScore.setSize(100, 40);
rightScore.setSize(100, 40);
add(leftScore);
add(rightScore);
}
I tried solutions which I found on here and other web-sites and they didn't work out well either. There is a .TTF file in a folder called 'assets' -which I created- in Java Project Folder named Pong. It would be perfect if the right code not include try and catch blocks.

private static Font fontAwesome;
static {
try (InputStream in = YOURCLASS.class.getClassLoader().getResourceAsStream("assets/fontawesome-webfont.ttf")) {
fontAwesome = Font.createFont(Font.TRUETYPE_FONT, in);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
}
Here's an example with fontawesome. Paste that at the top of your class and then simply use
leftScore.setFont(fontAwesome); to set the font.
Unfortunately you're going to need the try/catches. Note that the multicatch block might not work depending on your language level. If it doesn't just split them into two catch blocks.

Please try this:
try {
InputStream is = YourClass.class.getResourceAsStream("path/to/font");
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
Font sizedFont = font.deriveFont(18f);
jLabel.setFont(sizedFont);
} catch (Exception ex) {
System.err.println("Not loaded");}
After you load the font you need to set a size to it!
You will have to use try/catch blocks to do this.

Related

Java: Custom client can't read font

I have an enterprise application client and I want a custom font.
Exception:
java.io.IOException: Problem reading font data.
at java.awt.Font.createFont0(Font.java:1000)
at java.awt.Font.createFont(Font.java:877)
at de.fh_dortmund.inf.cw.surstwalat.client.user.view.LoginPanel.<init>(LoginPanel.java:68)
Code:
public void loaderFonts() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("resources/fonts/closeandopen.ttf")));
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("/resources/fonts/closeandopen.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(16f);
ge.registerFont(font);
} catch (IOException | FontFormatException e) {
System.err.println(e.getMessage());
// } finally {
// String[] fontnames = ge.getAvailableFontFamilyNames();
// for (String fontname : fontnames) {
// System.out.println(fontname);
// }
}
I tried a few things, but found no solution.
different fonts
different ways to see comments
paths
etc
maybe some ideas?

Java Cannot load a custom font from file and set JTextArea's font to it

So I'm trying to make a simple application, and I got a window appearing. The problem is that I require some special font, which I doubt would be installed on the user's OS, so I've got to load it from a file.
I've read countless articles and I've been stuck on this for quite a while and I'm not sure if the font isn't being loaded or it's not registering. I've also gotten confused with the type of "Stream" to use, because countless tries with InputStream, FileInputStream and BufferStream have lead to nothing.
The font is being copied to the output directory. This is my project structure
<packages-with-classes>
fonts
-> gameFont.ttf
This is the code I'm using
displayArea = new JTextArea();
displayArea.setEditable(false);
//FONT to give graphics (plz help me)
GraphicsEnvironment ge = null;
try {
//ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
/*Font initFont = Font.createFont(Font.TRUETYPE_FONT, Main.class.getClassLoader().getResourceAsStream("/fonts/gameFont.ttf") );
Font fontBase = initFont.deriveFont(Font.PLAIN, 20);*/
Font gameFnt = Font.createFont(Font.TRUETYPE_FONT, Main.class.getClassLoader().getResourceAsStream("fonts/gameFont.ttf")).deriveFont(Font.PLAIN, 12f);
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(gameFnt);
displayArea.setFont(gameFnt);
} catch (IOException e) {
e.printStackTrace();
} catch(FontFormatException e) {
e.printStackTrace();
}
So after a really really huge headache, I got it working :)
Here's the code if anyone else is stuck on the same problem:
InputStream fontStream = Main.class.getResourceAsStream("/fonts/gameFont.ttf");
try {
Font gameFont = Font.createFont(Font.TRUETYPE_FONT,fontStream);
gameFont=gameFont.deriveFont(Font.PLAIN, 14);
displayArea.setFont(gameFont);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}

add .ttf file to java project

I have downloaded akshar.ttf file and want to add it to my java project. I have tried the following ways by searching online but nothing worked so far.
Try 1:
Font ttfBase = null;
Font ttfReal = null;
try {
InputStream myStream = new BufferedInputStream(new FileInputStream("akshar.TTF"));
ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream);
ttfReal = ttfBase.deriveFont(Font.PLAIN, 24);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("akshar font not loaded.");
}
Try 2:
Font font = new Font("akshar",Font.PLAIN,15);
I have the akshar.ttf file at the following places:-
java/jre/lib/fonts
bin folder of my project
src folder of my project
I am new to java and have tried all these by following various links online. Please help me where am i going wrong.
You can register the created font with the graphics environment , as below :
try {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("akshar.TTF"));
} catch (IOException|FontFormatException e) {
//Handle exception
}
Refer the Java tutorial.
Put your ttf into the assests folder :)

Java not smoothing custom fonts

Me and my group are creating a web applet (entirely applet). However, I created a custom font to use for a banner but it won't use anti aliasing/font smoothing on it.
All the other normal fonts used work just fine but my custom font refuses to.
I'm using an opentype windows ttf font called FoundryMonoline.
try {
fontAd = Font.createFont(Font.TRUETYPE_FONT, new File("D:\\ATWDemo\\src\\FoundMonMed.ttf"));
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fontAd = fontAd.deriveFont(Font.TRUETYPE_FONT, 22);
SimpleAttributeSet sa = new SimpleAttributeSet();
StyleConstants.setAlignment(sa, StyleConstants.ALIGN_CENTER);
text_title.getStyledDocument().setParagraphAttributes(0,text_title.getStyledDocument().getLength(),sa,false);
text_title.setFont(fontAd);

Detecting if a final is blank in a constructor

I'm trying to create an enum for final Images, where the variable 'image' would be loaded from a file. If an IOException occurs, I want 'image' to be set to null. However, according to the compiler, 'image' may or may not be set when the catch block runs.
public enum Tile {
GROUND("ground.png"), WALL("wall.png");
final Image image;
Tile(String filename) {
try {
image = ImageIO.read(new File("assets/game/tiles/" + filename));
} catch (IOException io) {
io.printStackTrace();
image= null; // compiler error 'image may already have been assigned'
}
}
}
Final variables need to be set in the constructor, so if the image for some reason cannot be read, it has to be set to something. However, there's no way to tell whether or not image has actually been set. (In this case, the catch block only will run if no image is set, but the compiler says that it may have been set)
Is there a way for me to assign image to null in the catch block only if it hasn't been set?
Try using a local temporary variable:
public enum Tile {
GROUND("ground.png"), WALL("wall.png");
final Image image;
Tile(String filename) {
Image tempImage;
try {
tempImage= ImageIO.read(new File("assets/game/tiles/" + filename));
} catch (IOException io) {
io.printStackTrace();
tempImage= null; // compiler should be happy now.
}
image = tempImage;
}
}
Here is the solution I ended up using. It adds a method so that the code return if the ImageIO class does find an image, leaving no chance for the catch statement to be called.
public enum Tile {
GROUND("ground.png"), WALL("wall.png");
final Image image;
Tile(String filename) {
image = getImage(filename);
}
Image getImage(String filename) {
try {
return ImageIO.read(new File("assets/game/tiles/" + filename));
} catch (IOException io) {
io.printStackTrace();
return null;
}
}
}
However, this isn't really a way to detect a blank final variable. I'm hoping to see if there's a way to set a final variable inside a try/catch without going around the issue using temporary variables.

Categories