Skip to content

Instantly share code, notes, and snippets.

@qrtt1
Created February 1, 2014 15:08
Show Gist options
  • Select an option

  • Save qrtt1/8753469 to your computer and use it in GitHub Desktop.

Select an option

Save qrtt1/8753469 to your computer and use it in GitHub Desktop.
A simple font-viewer for java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
@SuppressWarnings("serial")
public class JavaFontsViewer extends JFrame {
JTextPane textPane;
Container container;
StyledDocument document = new DefaultStyledDocument();
public JavaFontsViewer() throws BadLocationException {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(800, 600);
setPreferredSize(new Dimension(800, 600));
setTitle("Java Fonts Viewer");
container = getContentPane();
container.setLayout(new BorderLayout());
textPane = new JTextPane(document);
container.add(new JScrollPane(textPane), BorderLayout.CENTER);
Style style = document.getStyle(StyleContext.DEFAULT_STYLE);
String originFontFamily = (String) style.getAttribute(StyleConstants.FontFamily);
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts(); // Get the fonts
for (Font f : fonts) {
style.addAttribute(StyleConstants.FontSize, 24);
style.addAttribute(StyleConstants.FontFamily, originFontFamily);
document.insertString(document.getLength(), f.getFontName() + " ", style);
style.addAttribute(StyleConstants.FontFamily, f.getFamily());
document.insertString(document.getLength(), f.getFontName() + " 字型檢視器\n", style);
}
textPane.setEditable(false);
setVisible(true);
}
public static void main(String[] args) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
new JavaFontsViewer();
} catch (BadLocationException e) {
e.printStackTrace();
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment