What font in Swing looks the same in all OS?

前端 未结 4 1314
[愿得一人]
[愿得一人] 2020-12-03 09:10

I use Netbeans 7.0 with JDK6 under Windows 7 to design the user interface of my Java application. I apply System look and feel. But it looks the way I want in Windows but di

4条回答
  •  Happy的楠姐
    2020-12-03 09:22

    An old question, but I've found it because I was looking for a solution. And my solution is: use DejaVu fonts. The Java dialog font looks different in Linux and Windows, but DejaVuSans 12 is very like the dialog font in Linux and looks the same in Windows (in Windows 8.1 at least). My code:

    ...
    static Font dejaVuSans;
    static final String resPath = "/resources/"; // no leading "/"
    ...
    public static void main(String[] args) {
        /* See:
         * https://stackoverflow.com/questions/7434845/setting-the-default-font-of-swing-program
         * https://stackoverflow.com/questions/8361947/how-to-get-getclass-getresource-from-a-static-context
         */
        dejaVuSans = null;
        Font f;
        try {
            InputStream istream = .class.getClassLoader().getResourceAsStream(
                resPath + "DejaVuSans.ttf");
            dejaVuSans = Font.createFont(Font.TRUETYPE_FONT, istream);
            f = dejaVuSans.deriveFont(Font.PLAIN, 12);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            f = null;
        }
        if (f == null)
            f = new Font("Dialog", Font.PLAIN, 12);
        java.util.Enumeration keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            Object value = UIManager.get (key);
            if (value != null && value instanceof javax.swing.plaf.FontUIResource)
                UIManager.put (key, f);
        }
        ...
    }
    

    Of course, if DejaVuSans.ttf is not embedded in the jar file you can import it at runtime. See How do you import a font?.

提交回复
热议问题