18

我想使用 TTF 文件创建一个新的 Font 对象。创建一个 Font 对象真的很简单,但是我不知道如何设置颜色和大小,因为我找不到它的方法?

InputStream is = new FileInputStream("helvetica.ttf");
Font helvetica = Font.createFont(Font.TRUETYPE_FONT, is);
4

4 回答 4

26

字体没有颜色;只有在使用字体时才能设置组件的颜色。例如,当使用 JTextArea 时:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

根据这个链接,createFont() 方法创建了一个新的字体对象,点大小为 1,样式为 PLAIN。所以,如果你想增加字体的大小,你需要这样做:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);
于 2013-05-26T17:06:53.697 回答
7

好吧,一旦你有了你的字体,你就可以调用deriveFont. 例如,

helvetica = helvetica.deriveFont(Font.BOLD, 12f);

将字体样式更改为粗体,将其大小更改为 12 磅。

于 2013-05-26T17:11:29.517 回答
0

因为字体没有颜色,所以您需要一个面板来制作背景颜色并为 JLabel(如果您使用 JLabel)和 JPanel 提供前景色来制作字体颜色,如下例所示:

JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);

JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);

标签的背景颜色为栗色,字体颜色为黄色。

于 2018-10-01T14:45:36.910 回答
-3

要设置字体的颜色,您必须首先通过执行以下操作来初始化颜色:

Color maroon = new Color (128, 0, 0);

完成此操作后,然后输入:

Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string

注意:1代表字体类型,可以用来替换Font.PLAIN,25代表字体大小。

于 2016-01-01T16:58:44.143 回答