java - 尝试使用 jtextfield 捕获异常?

标签 java swing user-interface

我正在制作一个简单的 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/

相关文章:

java - java中使用正则表达式进行模式匹配

java - 如何使用 Java POI 从工作簿中删除所有公式

java - "The value of the field speed is the average speed in knots"添加值

java - java中的条形码生成

java - 单击按钮应调用一个选项卡 Pane (动态),其中包含文本面板

java - 如何将 "listener"添加到 JList

java - 如何在 Java Swing 的同一窗口中显示菜单和面板?

java - 为什么Java ClassLoader加载这个类

c# - 使用 .NET 的现代 UI 桌面设计

java - 在 Java 中使用线程绘制面板