【问题标题】:try and catch exceptions with jtextfield?尝试使用 jtextfield 捕获异常?
【发布时间】:2019-08-02 04:06:23
【问题描述】:

我正在制作一个简单的 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());
    }
}

【问题讨论】:

  • 您可以查看JTextField的属性,有一个选项可以禁用字段中的字符输入(即只输入数值)

标签: java swing user-interface


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2011-12-05
    • 2014-05-11
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多