java 字体+颜色综合使用示例
java 字体+颜色综合使用示例
1 package com.wt010.jframe; 2 3 import java.awt.Color; 4 import java.awt.FlowLayout; 5 import java.awt.Font; 6 import java.awt.GraphicsEnvironment; 7 import java.awt.event.ActionEvent; 8 import java.awt.event.ActionListener; 9 10 import javax.swing.*; 11 12 /** 13 * @author konecms 14 * @date 2018年1月21日 15 * @version 1.0 16 */ 17 public class FontDemo extends JFrame implements ActionListener { 18 19 private final int[] iFontStyle={Font.PLAIN,Font.BOLD,Font.ITALIC,Font.BOLD|Font.ITALIC}; 20 private final String[] strFontStyleName={"普通","粗体","斜体","粗斜体"}; 21 private JButton btnSetFont,btnExit,btnColor; 22 private JComboBox cmbName,cmbSize,cmbStyle; 23 private JTextArea ta; 24 public FontDemo(){ 25 JPanel jp=new JPanel(); 26 jp.setLayout(new FlowLayout()); 27 getContentPane().add("North",jp); 28 29 JLabel lblName=new JLabel("字体:"); 30 String[] fontList=GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); 31 cmbName=new JComboBox(fontList); 32 33 cmbName.setSelectedItem("黑体"); 34 jp.add(lblName);jp.add(cmbName); 35 36 JLabel lblSize=new JLabel("大小"); 37 cmbSize =new JComboBox(); 38 for(int i=8;i<=18;i++){ 39 cmbSize.addItem(i+""); 40 } 41 cmbSize.addItem("36"); 42 cmbSize.addItem("48"); 43 cmbSize.addItem("72"); 44 cmbSize.setSelectedItem("14"); 45 jp.add(lblSize);jp.add(cmbSize); 46 47 48 JLabel lblStyle=new JLabel("样式:"); 49 cmbStyle=new JComboBox(strFontStyleName); 50 cmbStyle.setSelectedItem("粗体"); 51 jp.add(lblStyle);jp.add(cmbStyle); 52 53 54 btnSetFont=new JButton("设置(S)");btnSetFont.setMnemonic('S');btnSetFont.addActionListener(this); 55 btnColor=new JButton("颜色(C)");btnColor.setMnemonic('c');btnColor.addActionListener(this); 56 btnExit=new JButton("退出(X)");btnExit.setMnemonic('X');btnExit.addActionListener(this); 57 jp.add(btnSetFont);jp.add(btnColor);jp.add(btnExit); 58 59 ta=new JTextArea("邝伟林 \n湖南,永州\nHello myFont . ",8,30); 60 Font font0=new Font("微软雅黑",Font.BOLD,14); 61 ta.setFont(font0); 62 JScrollPane sp=new JScrollPane(ta);
getContentPane().add("Center",sp); 63 } 64 public static void main(String[] args) { 65 FontDemo fd=new FontDemo(); 66 fd.setTitle("字体的使用"); 67 fd.setLocationRelativeTo(null); 68 fd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 69 fd.pack(); 70 fd.setVisible(true); 71 } 72 73 @Override 74 public void actionPerformed(ActionEvent e) { 75 // TODO Auto-generated method stub 76 if(e.getSource()==btnSetFont){ 77 String fontName=(String) cmbName.getSelectedItem(); 78 int size = Integer.parseInt((String) cmbSize.getSelectedItem()); 79 int index= cmbStyle.getSelectedIndex(); 80 int style=iFontStyle[index]; 81 Font font=new Font(fontName,style,size); 82 ta.setFont(font); 83 } 84 if(e.getSource()==btnColor){ 85 JColorChooser chooser=new JColorChooser(); 86 Color color=chooser.showDialog(this, "拾取颜色", Color.orange); 87 ta.setForeground(color); 88 } 89 if(e.getSource()==btnExit){ 90 System.exit(0); 91 } 92 } 93 }
运行结果: