简体   繁体   English

尝试使用jtextfield捕获异常?

[英]try and catch exceptions with jtextfield?

I'm making a simple GUI where the user has to enter 2 random strings of numbers and when the done button is pushed it will output those 2 strings. 我正在制作一个简单的GUI,其中用户必须输入2个随机数字字符串,并且在按下完成按钮时,它将输出这2个字符串。 But how do I do this with try-catch method so that the user only can use numbers otherwise it will catch exceptions? 但是,我该如何使用try-catch方法来做到这一点,以便用户只能使用数字,否则它将捕获异常?

This is my code: 这是我的代码:

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());
    }
}

The isDigit(char) method may be useful for you. 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
}

Replace the WhateverException with any exception you need thrown there. WhateverException替换为您需要在此处引发的任何异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM