2013-03-15 68 views
3

我的OS X 10.8安装程序预先安装了11个字体,系列号为Helvetica Neue。我试图找到一种方法来访问字体样式介质浓缩,这不能由位掩码值Font.BOLDFont.ITALIC表示。如何使用Swing访问字体系列的所有字体

GraphicsEnvironment.getAllFonts()返回Font所有这些字体的对象,但应用它们使用JLabel.setFont()似乎只使用可用所提到的位掩码表示的样式。这在下面的屏幕截图的左侧显示,它将其与TextEdit中使用的所有字体样本进行比较。

如果使用字体的全名或PostScript名称构造Font对象,则会发生同样的情况。

是否有使用所有这些字体,或者通过将它应用于摇摆组件或画到Graphics2D(或Graphics)实例时的方法吗?

Output from the Swing application on the left, sample of all fonts on the right.

下面是我用于生产在上面的截图的对话框的代码。

package fahrplan; 

import java.awt.*; 
import javax.swing.*; 

public class FontsMain { 
    public static void main(String[] a) { 
     GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); 

     JPanel contentPane = new JPanel(); 
     contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); 

     for (Font i : e.getAllFonts()) { 
      String name = i.getFontName(); 

      if (name.startsWith("HelveticaNeue")) { 
       JLabel label = new JLabel(name); 

       label.setFont(i.deriveFont(18f)); 

       contentPane.add(label); 
      } 
     } 

     JFrame frame = new JFrame("Fonts"); 
     frame.setContentPane(contentPane); 
     frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 
+1

[你可以测试](http://stackoverflow.com/a/9022901/714968) – mKorbel 2013-03-15 17:22:55

回答

0

我会这样做。

int size=12, style=0; 

GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
final Font[] fonts = e.getAllFonts(); 
for(int i=0; i<fonts.length; i++) 
    { 
     JLabel label = new JLabel(Font[i].getName); 
     label.setFont(new Font(Font[i].getName, size, style)); 
     contentPane.add(label); 
    } 

我希望这会有所帮助。

+0

我现在可以发现的代码中唯一的区别是你使用12磅的字体大小而不是18.我认为这没有什么不同。 ;)第二张纸条上,你看过我的问题截图了吗? – Feuermurmel 2013-03-22 15:55:17

+0

这与我合作! – Hullu2000 2013-03-23 14:49:10

+0

我相信你!自从我发现这只发生在多种样式存储在同一个'.dfont'文件中的字体上,而我们使用的是独一无二的OS X.我仍然在寻找一种在Mac上使用所有这些样式的方法。 – Feuermurmel 2013-04-02 12:21:16

相关问题