import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.omg.CORBA.PUBLIC_MEMBER;
public class CheckImage {
public static void main(String[] args) {
JFrame frm = new JFrame("图片验证");
frm.setBounds(300, 50, 300, 200);
Container c= frm.getContentPane();
final JLabel label = new JLabel(getImageJLabel());
c.add(label,BorderLayout.NORTH);
JButton button = new JButton("下一张");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
label.setIcon(getImageJLabel());
}
});
final JTextField tfCodeField = new JTextField(20);
tfCodeField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
System.out.println("lost");
super.focusLost(e);
}
});
JPanel panel = new JPanel();
panel.add(button);
JButton button2 = new JButton("验证");
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String strNum = tfCodeField.getText().trim();
int num2 = Integer.valueOf(strNum);
if(num2==num){
JOptionPane.showMessageDialog(null, "验证成功");
}else{
JOptionPane.showMessageDialog(null, "验证失败");
}
}
});
panel.add(button2);
c.add(tfCodeField,BorderLayout.CENTER);
c.add(panel,BorderLayout.SOUTH);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
public static int num = -1;
public static Icon getImageJLabel(){
BufferedImage bufferedImage = new BufferedImage(50, 30, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) bufferedImage.getGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, 50, 30);
g2.setColor(Color.RED);
Font font = new Font("Fixedsys", Font.PLAIN, 20);
// 设置字体。
g2.setFont(font);
num = new Random().nextInt(10000);
while(num < 1000){
num = new Random().nextInt(10000);
}
g2.drawString(String.valueOf(num), 10, 20);
Icon icon = new ImageIcon(bufferedImage);
JLabel label = new JLabel(icon);
return icon;
}
}