我正在制作一个简单的GUI,用户必须输入2个随机数字字符串,然后按 done (完成)按钮将输出这2个字符串。但是,如何使用try-catch方法做到这一点,以便用户只能使用数字,否则它将捕获异常?
这是我的代码:
public Panel()
{
label1 = new JLabel("first string: ");
label2 = new JLabel("second string: ");
field1 = new JTextField(38);
field2 = new JTextField(3);
button1 = new JButton("done");
ButtonP buttonP = new ButtonP();
button1.addActionListener(buttonP);
this.add(label1);
this.add(field1);
this.add(label2);
this.add(field2);
this.add(button1);
}
private class ButtonP implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("String 1 " + field1.getText() + " and string 2 " + field2.getText());
}
}
答案 0 :(得分:0)
isDigit(char)
方法可能对您有用。
public void actionPerformed(ActionEvent e)
{
for(char c: field1.getText().toCharArray()) {
if(!Character.isDigit(c)) throw new WhateverException();
}
//Repeat this for field2's text as well
//do other things with the strings, at this point they are valid
}
将WhateverException
替换为您需要扔在那里的任何异常。