Saturday, July 20, 2013

Font

Font class represents fonts of text to display on a component. When constructing a new font object, you need to specify font name (logical name), style, and font size.

Font constructor:
-Font(String fontname,int style, int size)
Useful fields:
-BOLD
-ITALIC
-PLAIN
Useful methods:
-getName():String
-getSize():int
-getStyle():int
-isBold():boolean
-isItalic():boolean
-isPlain():boolean

In the example below, a new Tahoma font with Bold style, and 30 in size is created. To apply the font to the text to be drawn on the Canvas, you need to the setFont(Font font) method by supplying the created font to this method argument.

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.ImageObserver;

class DrawArea extends Canvas implements ImageObserver{
public void paint(Graphics g){

Font f=new Font("Tahoma",Font.BOLD,30);
g.setFont(f);
g.drawString("Hello, World!", 300,100);


}
}
class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(600,400);
setVisible(true);
add(new DrawArea());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AWTTEST {
public static void main(String[] args){

new WindowShow("Using font");

}


}


List all font in the system

To get all fonts in the system, you can use the getAllFonts() method of the GraphicsEnvironment class.

Example:
public static void showFonts(){
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts=ge.getAllFonts();
for(Font f:fonts){
System.out.println(f.getName());
}
}

No comments:

Post a Comment