Java繪圖中,顯示文字的方法主要有三種:
(1)drawString(String str,int x,int y):在指定的位置顯示字符串。
(2)drawChars(char data[],int offset,int length, int x, int y):在指定的位置顯示字符數組中的文字,從字符數組的offset位置開始,最多顯示length個字符。
(3)drawBytes(byte data[],int offset,int length,int x,int y), 在指定的位置顯示字符數組中的文字,從字符數組的offset位置開始,最多顯示length個字符。
這里給出的顯示位置(x,y)為文字的基線的開始坐標,不是文字顯示的矩形區域的左上角坐標。
文字字型有三個要素:
字體:常用的字體有Times New Roman、Symbol、宋體、楷體等。
風格:常用的風格有三種:正常、粗體和斜體;分別用三個常量表示:Font.PLAIN(正常)、Font.BOLD(粗體)和Font.ITALIC(斜體)。風格可以組合使用,例如 ,Font.BOLD+Font.ITALIC。
字號:字號是字的大小,單位是磅。
在Java語言中,用類Font對象字型。Font類構造方法有:
Font(String fontName,int style,int size),3個參數分別表示字體、風格和字號。例如,代碼:
Font fnA = new Font(“細明本”,Font.PLAIN,12)
設置的字型的是:細明體、正常風格, 12磅字號。
Font類的其他常用方法:
- getStyle(),返回字體風格。
- getSize(),返回字體大小。
- getName(),返回字體名稱。
- isPlain(),測試字體是否是正常字體。
- isBold(),測試字體是否是粗體。
- isItalic(),測試字體是否是斜體。
【例】小應用程序用6種字型字符串,顯示內容說明本身的字型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import java.applet.*; import java.awt.*; public class Example7_1 extends Applet{ Font f1 = new Font( "Helvetica" ,Font.PLAIN, 18 ); Font f2 = new Font( "Helvetica" , Font.BOLD, 10 ); Font f3 = new Font( "Helvetica" ,Font.ITALIC, 12 ); Font f4 = new Font( "Courier" ,Font.PLAIN, 12 ); Font f5 = new Font( "TimesRoman" , Font.BOLD+Font.ITALIC, 14 ); Font f6 = new Font( "Dialog" ,Font.ITALIC, 14 ); public void paint(Graphics g){ setSize( 250 , 200 ); g.setFont(f1);drawString( "18pt plain Helvetica" , 5 , 20 ); g.setFont(f2);drawString( "10pt bold Helvetica" , 5 , 43 ); g.setFont(f3);drawString( "12pt italic Helvetica" , 5 , 58 ); g.setFont(f4);drawString( "12pt plain courier" , 5 , 75 ); g.setFont(f5);drawString( "14pt bold & italic times Roman" , 5 , 92 ); g.setFont(f6);drawString( "14pt italic dialog" , 5 , 111 ); } } |
用類Color的對象設置顏色,有兩種方法生成各種顏色:
用類Color預定議的顏色:black,red, white, yellow ……;
通過紅綠藍(RGB)的值合成顏色。
與顏色有關的常用方法:
(1)用類Color的構造方法Color(int R, int G,int B)創建一個顏色對象,參數R,G,B分別表示紅色、綠色和藍色,它們的取值是從0到255。
(2)用類Graphics的方法setColor(Color c),參數c的取值參見表12-1。
(3)用類Component的方法setBackground(Color c)設置背景顏色。因為小程序是組件類的子類,直接可用setBackground()方法改變背景色。
(4)用類Graphics的方法getColor()獲取顏色。
Color 類預定義顏色常量
【例】小應用程序設置顏色并涂方塊,其中繪制方塊的方法將在后續小節中講到。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import java.applet.*; import java.awt.*; public class Example7_2 extends Applet{ public void paint(Graphics g){ setSize( 380 , 200 ); for ( int i= 0 ;i<= 10 ;i++){ Color myredcolor = new Color(i* 25 + 5 , 0 , 0 ); g.setColor(myredcolor); g.fillRect(i* 32 + 5 , 2 , 28 , 28 ); } for ( int i= 0 ;i<= 10 ;i++){ Color mygreencolor = new Color( 0 ,i* 25 + 5 , 0 ); g.setColor(mygreencolor); g.fillRect(i* 32 + 5 , 32 , 28 , 28 ); } for ( int i= 0 ;i<= 10 ;i++){ Color mybluecolor = new Color( 0 , 0 ,i* 25 + 5 ); g.setColor(mybluecolor); g.fillRect(i* 32 + 5 , 62 , 28 , 28 ); } } } |