代码思路:
设置一个按钮适配器进行监听
A到Z与0到9存储在数组中,随机抽取四位数输出到文本域中
代码实现:
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.event.AncestorListener;
public class YanZhengMa {
//定义私有成员变量
private JFrame jf;
private JPanel jp;
private JButton jb;
private JTextArea jt;
public static String codeGen() {
char[] codeSequence = {'A','B','C','D','E','F','G','H','I','G','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0'};
Random random = new Random();
//不用String是因为String定义的变量不能改变
StringBuffer sb = new StringBuffer();
int count = 0;
String cry = "";
while (true) {
//利用获取下表获取数组中的单个数值
char c = codeSequence[random.nextInt(codeSequence.length)];
//对单个数值进行判断是否为空,不为空则继续执行
if (sb.indexOf(c+"") == -1) {
sb.append(c);
count++;
//当满四个数值的时候终止循环
if (count == 4) {
break;
}
}
cry += c;
}
return cry = sb.toString();
}
public YanZhengMa(){
jf = new JFrame("随机号码");
jp = new JPanel();
jb = new JButton("刷新");
jt = new JTextArea("");
jf.add(jp);
//设定表格布局东中
jp.setLayout(new BorderLayout());
jb.setBounds(120, 20, 50, 40);//划定的按钮尺寸
jp.add(jb , BorderLayout.EAST);
jp.add(jt , BorderLayout.CENTER);
//设置按钮监听器
jb.addActionListener(new MyClick());
// MyClick src = new MyClick();
//设置窗口框架的大小与坐标
jf.setSize(300,100);
jf.setLocation(300, 300);
//确保窗口正常显示与关闭
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
//内部类适配器实现ActionListener()类,重写里面的方法
class MyClick implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//将构造方法赋值给字符串
String cry = YanZhengMa.codeGen();
//下面是获取按钮的值,此处不用
String text = ((JButton)e.getSource()).getText();
jt.append("验证码是:"+cry+"\n");
}
}
public static void main(String[] args) {
YanZhengMa cty = new YanZhengMa();
}
}