我正在制作一个简单的 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());
}
}
最佳答案
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
替换为您需要抛出的任何异常。
关于java - 尝试使用 jtextfield 捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55108701/