java Applet 程序設計講解2 字體,顏色的使用
java Applet 程序設計講解2 字體,顏色的使用
關鍵詞: 字體 顏色
圖形界面輸出用到的字體,顏色的使用
1、字體類 (Font類)
構造方法:
Font(String fontname,int style,int size)
fontname: 字形名稱,例如:“黑體”,“宋體”
style: 字體樣式:整形常量,常使用Font類定義好的常量
size: 用象素點表示的字符大小
常用成員方法:
獲取字體對象信息的方法:
getName(), getStyle(), getSize()
判斷字體樣式的方法:
isPlain() ,isBold(),
例2 用指定的字體輸出文本
import java.awt.Graphics;
import java.awt.Font;
public class FontDemo extends java.applet.Applet{
public void paint(Graphics g){
Font ftp20 = new Font("TimesRoman",Font.PLAIN,20);
Font fai15 = new Font("Arial",Font.ITALIC,15);
Font fcb24 = new Font("Courier",Font.BOLD,24);
Font fsib30 = new Font("宋體",Font.ITALIC+Font.BOLD,30);
g.setFont(ftp20);
g.drawString("Font name TimesRoman , style plain , size 20",10,20);
g.setFont(fai15);
g.drawString("Font name Arial , style italic , size 15",10,50);
g.setFont(fcb24);
g.drawString("Font name Courier , style bold , size 24",10,80);
g.setFont(fsib30);
g.drawString("字體名 宋體,風格 斜體+粗體,尺寸 30",10,120);
}
}
例3 獲取字體信息
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Font;
public class GetFontInfo extends Applet
{
Font f=new Font("TimesRoman",Font.ITALIC+Font.BOLD,24);
public void paint(Graphics g)
{
int style,size;
String s,name;
g.setFont(f);
style=f.getStyle();
switch (style)
{
case Font.PLAIN : s=" Plant ";
case Font.BOLD : s=" Bold ";
case Font.ITALIC: s=" Italic ";
case Font.BOLD+Font.ITALIC : s=" Bold itali c";
default: s=" ";
}
size =f.getSize();
s+=size+" point";
name=f.getName();
s+=name;
g.drawString(s,10,50);
g.drawString("Font family is "+f.getFamily(),10,100);
}
}
2、顏色類
Color類定義了多個有關顏色的常量和方法。
構造方法:
Color c=new Color(redint,greenint,blueint)
顏色的使用
顏色color是一個類,必須通過創(chuàng)建對象來使用。
使用顏色的方法一:
使用r,g,b來表示顏色。通過下面方法創(chuàng)建顏色:
Color c=new Color(redint,greenint,blueint)
例 利用該方法輸出不同顏色的字符
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
public class ColorDemo extends java.applet.Applet{
public void paint(Graphics g){
int red,green,blue;
Font f=new Font("TimesRoman",Font.PLAIN,30 );
g.setFont(f);
for (int i=30;i<=300;i+=30)
{
red=(int)Math.floor(Math.random()*256);
green=(int)Math.floor(Math.random()*256);
blue=(int)Math.floor(Math.random()*256);
g.setColor(new Color(red,green,blue));
g.drawString("Different Color String : red="+red+" green="+green+
" blue="+blue,1,i);
}
}
}
使用顏色的方法二:
使用Color類中定義的標準顏色Color對象
例:使用顏色的方法的演示
import java.awt.*;
import java.applet.*;
public class ColorSet1 extends Applet {
Font f=new Font("TimesRoman",Font.PLAIN,30 );
Color c=Color.BLUE; //標準顏色Color對象
public void paint(Graphics g)
{
g.setFont(f);
g.setColor(c);
g.drawString("Welcome to Java!! This is Color demo", 50, 60 );
g.drawString("current RGB:"+String.valueOf(c.getRed())+" "+
String.valueOf(c.getGreen())+" "+
String.valueOf(c.getBlue()), 50, 120 );
}
}