(1)函数说明:
字形类Font用于规范组件所使用的字形大小、样式和字体等。其构造函数:
public Font(String name,int style,int size);
name表示本地可获取字体名称
style表示字体样式,包含Font.PLAIN,Font.BOLD,Font.ITALIC三种,分别对应平体、加粗和斜体。
一个有用的方法用来获取本地可用字体
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fa=ge.getAvailableFontFamilyNames();
通过从绘图环境中获取到本地可用的字体名数组。
(2)代码 用指定的字型约束来显示窗体上的字。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GraExp extends JFrame
{
CInstead c1=new CInstead();
Container c;
String[] zt;
String[] zx={ "平体" ,"加粗" ,"斜体" } ;
String name="Serif" ;
int type=0;
int size=12;
JLabel lbl1=new JLabel("字体:" );
JLabel lbl2=new JLabel("字形:" );
JLabel lbl3=new JLabel("字号:" );
JLabel lbl=new JLabel("测试用字abcABC123" );
JComboBox cb1,
cb2=new JComboBox(zx);
JTextField tf1=new JTextField(25),
tf2=new JTextField(10);
public GraExp()
{
//获取可用字体名称数组
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
zt=ge.getAvailableFontFamilyNames();
cb1=new JComboBox(zt);
setContentPane(c1);
c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT));
c.add(lbl1);
c.add(cb1);
c.add(lbl2);
c.add(cb2);
c.add(lbl3);
c.add(tf1);
lbl.setPreferredSize(new Dimension(200,60));
lbl.setForeground(Color.red);
c.add(lbl);
cb1.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent event)
{
int state=event.getStateChange();
name=(String) event.getItem();
setCustomFont(name,type,size);
}
} );
cb2.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent event)
{
int state=event.getStateChange();
String s=(String) event.getItem();
if (s.equals("平体" )){
type=Font.PLAIN;
} else if (s.equals("加粗" )){
type=Font.BOLD;
} else {
type=Font.ITALIC;
}
setCustomFont(name,type,size);
}
} );
tf1.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e)
{
int c=e.getKeyCode();
if (c==10)
{
String s=tf1.getText();
size=Integer.parseInt(s);
setCustomFont(name,type,size);
}
}
} );
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setSize(new Dimension(400,300));
show();
}
public static void main(String[] args)
{
GraExp ge=new GraExp();
}
private void setCustomFont(String name,int type,int size)
{
lbl.setFont(new Font(name,type,size));
lbl.revalidate();
}
class CInstead extends JPanel
{
ImageIcon icon;
Image img;
public CInstead()
{
icon=new ImageIcon(CInstead.class.getResource("333.png" ));
img=icon.getImage();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img,0,0,null );
}
}
}
程序效果: