Search code examples
javaactionlistenerjtextfield

reading user input and detecting type of entry in Java


In my program, I have a JTextField reading the user input. The user is supposed to enter a number and then click a JButton to confirm the entry, but i want to have a catch where if the user does not enter a number, a pop-up appears telling the user it is an incorrect input. How would I implement something to detect whether or not the user enters a number when the JButton is clicked? if i need to give more code, let me know.

JButton okay = new JButton("OK");
JTextField dataEntry = new JTextfield();

okay.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){       
        firstEntry = Float.parseFloat(dataEntry.getText());
        //want to see if it's a float, if true, run the following code
        confirm = true;
        changeText();
        dataEntry.setText("");
    }
});

Solution

  • parseFloat throws a NumberFormatException if the passed String does not contain a parseable float. You can catch this exception to detect whether the user has entered a float:

    try {
      firstEntry = Float.parseFloat(dataEntry.getText());
    } catch (NumberFormatException e) {
      // input is not a float
    }
    

    Another option is to use a Scanner if you don't want to be handling exceptions:

    Scanner scanner = new Scanner(dataEntry.getText());
    if (scanner.hasNextFloat()) {
      firstEntry = scanner.nextFloat();
    } else {
      // input is not a float
    }