我想在application里实现随机验证码.不过不知道为什么不能下一张.
代码如下:
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.*;
import java.util.*;
public class RandomNumberPanel extends JPanel{
private String strRand;
private JLabel jlabel;
public RandomNumberPanel(){
jlabel=new JLabel();
this.add(jlabel);
getRandomImage();
}
private Color getRandomColor(int fc,int bc){
Random ra=new Random();
if(fc> 255) fc=255;
if(bc> 255) bc=255;
int r=fc+ra.nextInt(bc-fc);
int g=fc+ra.nextInt(bc-fc);
int b=fc+ra.nextInt(bc-fc);
return new Color(r,g,b);
}
public void nextImage(){
getRandomImage();
}
private void getRandomImage(){
int width=50;
int height=20;
try{
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
Random r=new Random();
g.setColor(getRandomColor(200,250));
g.fillRect(0,0,width,height);
g.setFont(new Font( "Times New Roman ",Font.PLAIN,18));
g.setColor(getRandomColor(160,200));
for(int i=0;i <160;i++){
int x=r.nextInt(width);
int y=r.nextInt(height);
int x1=r.nextInt(12);
int y1=r.nextInt(12);
g.drawLine(x,y,x+x1,y+y1);
}
String sRand= " ";
for(int i=0;i <4;i++){
String s=String.valueOf(r.nextInt(10));
sRand+=s;
g.setColor(new Color(20+r.nextInt(110),20+r.nextInt(110),20+r.nextInt(110)));
g.drawString(s,13*i+6,16);
}
strRand=sRand;
g.dispose();
ImageIO.write(image, "JPEG ",new FileOutputStream( "tmp.jpg "));
jlabel.setIcon(new ImageIcon( "tmp.jpg "));
}catch(Exception e){
e.printStackTrace();
}
//this.remove(jlabel);
//this.add(jlabel);
SwingUtilities.updateComponentTreeUI(this);
}
public String getRandomString(){
return this.strRand;
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyDemo extends JFrame implements ActionListener{