为了处理异常写了很垃圾的代码
上的是实现只允许在JTextField中输入数字,当输入非数字时抛出自定义异常。InvalidateInputException但由于BadLocationException异常也要在insertString方法中处理,不知道怎么同时处理这两个异常,就写出了下面的垃圾代码,JAVA的异常处理真让人郁闷。不知道哪位大哥能帮忙改改。
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class numfield
{
public static void main(String[] args) throws InvalidateInputException {
JFrame frame = new JFrame();
frame.setTitle("NumOnlyField");
frame.setSize(120,80);
JPanel panel = new JPanel();
frame.add(panel);
JTextField numonly = new JTextField(new NumberField(),"",10);
panel.add(numonly);
frame.setVisible(true);
}
}
class NumberField extends PlainDocument {
public void insertString (int offset,String str,AttributeSet att) throws BadLocationException {
char[] source = str.toCharArray();
for(char c:source) {
if(Character.isDigit(c)) {
super.insertString(offset,str,att);
}
else {
try {
exception();
} catch (InvalidateInputException e) {
;
}
}
}
}
private void exception () throws InvalidateInputException {
InvalidateInputException e = new InvalidateInputException("NO");
throw e;
}
}
class InvalidateInputException extends Exception
{
public InvalidateInputException(String message) {
System.out.println(""+message);
}
}