Is there any way to accept only numeric values in a JTextField?

前端 未结 19 1916
陌清茗
陌清茗 2020-11-22 03:10

Is there any way to accept only numeric values in a JTextField? Is there any special method for this?

19条回答
  •  误落风尘
    2020-11-22 03:56

    A very easy solution is to use a action listener.

    TextFieldActionPerformed(java.awt.event.ActionEvent evt) {
        String textFieldValue = TextField.getText();
        try {
            Integer.parseInteger(textFieldValue);
        } catch(Exception e){
            JOptionPane.showMessageDialog(null, "Please insert Valid Number Only");
            TextField.setText(textFieldValue.substring(0,textFieldValue.length()-1));
        }
    }
    

    You Can use it for Double as well:

    Double.parseDouble(TextField.getText());
    

提交回复
热议问题