Bogdan M.
Bogdan M.

Reputation: 2181

NumberFormatException when converting from JTextField

My GUI program crashes when I convert from JTextField to int. Could help me review this code segment and see what is wrong, since I used the same method, and it worked.

What I do:

new JTextLabel l;

get whats there with

String A = l.getText() >int i = Interger.parse(A);

Code:

btnAdd.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int nr = Integer.parseInt(txtApt.getText());
        int nrP = Integer.parseInt(txtNrPips.getText());
        String owner = txtOwner.toString();
        Apartment a = new Apartment(nr, nrP, owner, false);
        Expense b = new Expense(Float.parseFloat(textWW.getText()), Float.parseFloat(textCW.getText()),
                Float.parseFloat(textGAS.getText()), Float.parseFloat(txtELEC.getText()), Float.parseFloat(textHEAT.getText()));
        ArrayList<Expense> l = new ArrayList<>();
        l.add(b);
        cont.addKeyWithList(a,l);
    }
});

Stack:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at gui.Gui$4.actionPerformed(Gui.java:195)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Upvotes: 1

Views: 6224

Answers (3)

ved
ved

Reputation: 909

The problem creates when you convert that string that can not convert into number. for eg : There is 2 string variable , one is "3" and other is "three". In later case , when you try to convert into integer , it will give NumberFormatException.

Same problem exists here , if you don't provide any value in text field , it is blank and exception occurs.

So , for get rid of exception. First check getText() value should not be null and blank and after that apply regular expression to check it will accept only numbers not alphabets and special char.

Upvotes: 1

Mel Nicholson
Mel Nicholson

Reputation: 3225

Some of your text fields do not have valid numeric content, which is choking the parse. TO fix this, you need to pre-filter your data.

float floatWW = MY_DEFAULT_VALUE;
boolean errorWW = false;
try {
  float floatWW = Float.parseFloat(textWW.getText());
} catch (NumberFormatException ex) {
  errorWW = true;
}

(And so on for each of you parseFloat calls)

Next you can decide whether to display an error or just accept defaults when given bad iuput.

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Your problem is that this method is being called when one or more JTextFields are empty, and the error occurs when you try to parse "" to an int. A solution is to block this method from being called if this occurs. You could for instance use a DocumentListener to your JTextField Documents to see if the JTextFields have text and to keep your JButton disabled until text is present in all necessary text fields.

Also, do use a try / catch block as I suggested above to trap exceptions and handle them gracefully:

btnAdd.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      try {
        int nr = Integer.parseInt(txtApt.getText());
        int nrP = Integer.parseInt(txtNrPips.getText());
        // ... etc ...
      } catch (NumberFormatException nfe) {
        // warn the user that the textfields are not parsing well.
      }
    }
});

Upvotes: 5

Related Questions