/*7:使用图形输出验证码效果(随机数字)
*Cavas Random Graphics
* */import java.awt.Button;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;public class Exseven extends Frame implements ActionListener {
Button b1;
Canvas c;
Random ra=new Random();
//定义一个字符串数组,用随机数从这里随机取出四个字符
char st[]="1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public Exseven() {
b1 = new Button("验证码");
c = new Canvas();
c.setBackground(new Color(ra.nextInt(256),ra.nextInt(256),ra.nextInt(256)));//画布背景随机色彩
c.setSize(180, 70);
add(c);
add(b1);
b1.addActionListener(this);
setLayout(new FlowLayout());
setSize(300, 150);
setVisible(true);
} public static void main(String[] args) {
new Exseven();
} public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1){
Graphics g=c.getGraphics();
Graphics g1=c.getGraphics();
c.paint(g);
//为什么在这里加上随机背景色之后验证码就显示不出来了??
//c.setBackground(new Color(ra.nextInt(256),ra.nextInt(256),ra.nextInt(256)));
Font f=new Font("Fixedsys",Font.PLAIN,50);
g1.setColor(new Color(ra.nextInt(256),ra.nextInt(256),ra.nextInt(256)));
g.setColor(new Color(ra.nextInt(100),ra.nextInt(100),ra.nextInt(100)));//设置验证码随机色彩
g.setFont(f);
//随机生成四个数字与字母的组合,+""必须有,意思是把四个字符连结起来变成字符串String
String ss=new String(st[ra.nextInt(36)]+""+st[ra.nextInt(36)]+st[ra.nextInt(36)]+st[ra.nextInt(36)]);
g.drawString(ss, 20, 50);
g1.drawLine(10, 10, 170, 60);
g1.drawLine(10, 40, 170, 20);
}
}
}如上,按钮事件代码中的注释,为什么我加上那一句验证码就显示不出来了呢??画布的背景色倒是变了,但是验证码却没有显示出来,郁闷了~~~请大伙们帮帮忙看看..谢谢了!!!
是不是要用到repaint()?对画布重绘?我试了一下,没有效果,我也不清楚它怎么用的~~请指教!!!谢谢~~~
建议改成
g.setColor(new Color(ra.nextInt(256),ra.nextInt(256),ra.nextInt(256)));
g.fillRect(0, 0, 180, 70);
,不想找,6楼的做法是可以的,我做的时候也是同6楼一样
程序源代码:
http://blog.csdn.net/huadis/archive/2009/06/24/4296146.aspx
还想问一下..如果按我原来的程序结构去改应该怎么改?
非常感谢了~~~
我写的主要是扩展了JComponent组件,用它来充当你的画布组件,当点击按钮时调用画布的repaint方法往组件上绘制内容。