最近在更新一些教学案例,突然想起每年支付宝都有一个扫福活动,就想着能不能用程序写一个福字,显而易见这当然可以,于是就有了这篇博文
其实内容很简单,主要就是三个类,一个是字体工具类,二是图片工具类,三是生成福字主类,效果如下
1、字体工具类import java.awt.*;
public class FontUtil {
public static void drawWord(Graphics g,String str,Color color,int size,int x,int y,String font){
g.setColor(color);
g.setFont(new Font(font,Font.BOLD,size));
g.drawString(str,x,y);
}
}
2、图片工具类
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImgTool {
//提取图片工具1
public static BufferedImage getimg(String path){
BufferedImage img=null;
try {
img= ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
//工具2
public static Image getImage(String filename){
return Toolkit.getDefaultToolkit().getImage(filename);
}
}
3、生成"福"主类
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;
public class RandFu extends JFrame {
List colorList;
List arrayList;
Integer index, fontRandom;
BufferedImage bg = null;
public RandFu() {
arrayList = Arrays.asList("楷体", "宋体", "华文琥珀", "华文行楷", "幼圆", "华文新魏", "华文彩云", "隶书");
fontRandom = (int) ((Math.random() * 10) % 8);
System.out.println("字体:" + arrayList.get(fontRandom));
bg = ImgTool.getimg("src/cn/img/bg.jpg");
// 初始化
colorList = Arrays.asList(Color.gray, Color.black, Color.PINK, Color.orange, Color.RED);
index = (int) ((Math.random() * 10) % 5);
System.out.println("字体颜色" + index);
setSize(600, 600);
setIconImage(ImgTool.getImage("src/cn/img/fu.png"));
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setBackground(Color.red);
// 键盘监听
// 设置面板键盘监听
this.addKeyListener(new KeyAdapter() {
// 重写键盘监听方法
@Override
public void keyPressed(KeyEvent e) {
// 判断是否是空格
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
reGame();
}
}
});
}
// 重启
public void reGame() {
// 关闭当前窗口
this.dispose();
// 开启新窗口
String[] args = {};
main(args);
}
@Override
public void paint(Graphics g) {
// 画背景
g.drawImage(bg, 15, 50, 570, 535, null);
FontUtil.drawWord(g, "福", colorList.get(index), 250, 163, 400, arrayList.get(fontRandom));
// repaint();
}
public static void main(String[] args) {
RandFu randFu = new RandFu();
}
}
源码点我下载



