簡體   English   中英

Font.createFont(..)設置顏色和大小(java.awt.Font)

[英]Font.createFont(..) set color and size (java.awt.Font)

我想使用TTF文件創建一個新的Font對象。 創建一個Font對象非常簡單,但我不知道如何設置顏色和大小,因為我找不到它的方法?

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

字體沒有顏色; 只有在使用字體時,您才能設置組件的顏色。 例如,使用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 font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

好吧,一旦你有了你的字體,就可以調用deriveFont 例如,

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

將字體的樣式更改為粗體,將其大小更改為12磅。

因為字體沒有顏色,所以需要一個面板來制作背景顏色並為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);

標簽的背景顏色是栗色,帶有黃色字體顏色。

要設置字體的顏色,必須首先通過執行以下操作初始化顏色:

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表示字體的大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM