Skip to content

Instantly share code, notes, and snippets.

@teocci
Last active July 12, 2016 07:33
Show Gist options
  • Save teocci/f428a59741cde8ad61d67fec8462da23 to your computer and use it in GitHub Desktop.
Save teocci/f428a59741cde8ad61d67fec8462da23 to your computer and use it in GitHub Desktop.
Java test for pre-load fonts (and apply properties) outside of the context of the paint method. Painting should run as fast as possible and will be called multiple times, sometimes in quick succession. Loading resources within any paint method wastes time and resource...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FontTest {
public static void main(String[] args) {
new FontTest();
}
public FontTest() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new FontTesterPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class FontTesterPane extends JPanel {
public FontTesterPane() {
try {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font f = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Triforce.ttf"));
if (!ge.registerFont(f)) {
System.out.println("Unable to register font");
}
f = f.deriveFont(Font.PLAIN, 24);
setFont(f);
} catch (IOException e) {
e.printStackTrace();
} catch (FontFormatException e) {
e.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
FontMetrics fm = g2d.getFontMetrics();
String text = "Kseek: Hello world";
int x = (getWidth() - fm.stringWidth(text)) / 2;
int y = ((getHeight() - fm.getHeight()) + fm.getAscent()) / 2;
g2d.drawString(text, x, y);
g2d.dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment