实训要求:
使用两个下拉框分别存放字体和字号的选项。其中字体从当前操作系统中获取。
选择字体和字号后,文本区中的文字会相应改变。
代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FontChange extends JFrame implements ItemListener {
JComboBox fontName;
JComboBox fontSize;
JTextArea txtContent;
Font font;
final String[] fontArr;
final String strArr = "去年今日此门中,\n" + "人面桃花相映红。\n" + "人面不知何处去,\n"
+ "桃花依旧笑春风。";
final String[] sizeArr = { "8", "9", "10", "12", "14", "16", "18", "20",
"24", "28", "32", "36", "40", "44", "48", "54", "60", "66", "72",
"80", "88", "96" };
public FontChange() {
super("改变字体");
txtContent = new JTextArea();
txtContent.setText(strArr);
JScrollPane jsp = new JScrollPane(txtContent);
GraphicsEnvironment env = GraphicsEnvironment
.getLocalGraphicsEnvironment();
fontArr = env.getAvailableFontFamilyNames();
fontName = new JComboBox(fontArr);
fontSize = new JComboBox(sizeArr);
fontSize.setPreferredSize(new Dimension(80, 27));
fontName.addItemListener(this);
fontSize.addItemListener(this);
fontName.setSelectedItem("宋体");
fontSize.setSelectedItem("16");
FlowLayout layout = new FlowLayout(FlowLayout.CENTER, 40, 5);
JPanel pan = new JPanel(layout);
pan.add(fontName);
pan.add(fontSize);
Container c = this.getContentPane();
c.add(pan, BorderLayout.NORTH);
c.add(jsp, BorderLayout.CENTER);
this.setSize(400, 300);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent e) {
String s = (String) fontName.getSelectedItem();
int n = Integer.parseInt((String) fontSize.getSelectedItem());
font = new Font(s, Font.PLAIN, n);
txtContent.setFont(font);
}
public static void main(String[] args) {
new FontChange();
}
}
运行结果: