當在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,"註冊成功");
}
}
}