当在TextField中要求输入汉字或英文字母,用户输入数字是也不会报错!但这并不是我们想要它实现的……
package bzu.edu.cn;
import javax.swing.*;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Aa {
public static void main(String[] args) {
new A();
}
}
class A implements ActionListener{
Frame fr=new Frame("注册员工姓名(中/英文)");
JTextField te;
JButton bu;
public A(){
fr.setLayout(null);
fr.setBounds(500,300,300,300);
te=new JTextField();
te.setSize(120,30);
te.setBounds(80,60,120,30);
bu=new JButton("确定");
bu.setBounds(200,60,60,30);
bu.addActionListener(this);
te.addActionListener(this);
fr.add(te);
fr.add(bu);
fr.setResizable(false);
fr.setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
class B{ //定义一个局部内部类
public boolean be() throws NumberFormatException{ //声明会产生输入格式不正确异常
String s=te.getText();
int se=Integer.parseInt(s);
if(se/1==se)
return false;
else
return true;
}
}
try{ //在调用be()方法并捕获其中的异常
if(new B().be()==false)
JOptionPane.showMessageDialog(null,"你输入的数据格式不正确,请输入字母或文字");
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null,"注册成功");
}
}
}