Search code examples
javaswingparsingjtextfieldnumberformatexception

How can I parse a value from a JTextField into an Integer and perform some math operations on it?


So, I've been trying to make a Celsius converter in Java using swing and got stuck on getting the input from the JTextField and parsing it into an Integer so i can perform an equation on it. If I leave it as a String I am unable to do any math operations.

I've added a private string called cValue in which I store the value of text field in, and then I have some code in the ActionListener that parses that string into an Integer.

When I run the program it opens up the window without any problems. I can type in anything in the text field, but as soon as I press the button the program exits out and I'm shown an error which I can't understand. If I move the code out of the action listener and run the program, it gives me an error.

Now, I'm pretty new to Java and am not that familiar with it yet. I wrote this using eclipse and made the UI with WindowBuilder. I've tried many things and nothing has worked so far. I appreciate any form of feedback I can get.

This is the code:

private String cValue; 
private String result = "0";
private JPanel contentPane;
private JTextField celsiusField;
private JButton convertButton;

/**
 * Create the frame.
 */
public CelsiusConverter() {

    setDefaultCloseOperation(CelsiusConverter.EXIT_ON_CLOSE);
    setBounds(100, 100, 194, 134);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblCelsius = new JLabel("Celsius");
    lblCelsius.setBounds(10, 11, 61, 14);
    contentPane.add(lblCelsius);

    celsiusField = new JTextField();
    celsiusField.setBounds(81, 8, 86, 20);
    contentPane.add(celsiusField);
    celsiusField.setColumns(10);

    JLabel lblFahrenheit = new JLabel("Fahrenheit:");
    lblFahrenheit.setBounds(10, 73, 70, 14);
    contentPane.add(lblFahrenheit);

    JLabel lblResult = new JLabel();
    lblResult.setText(String.valueOf(result));
    lblResult.setBounds(81, 73, 87, 14);
    contentPane.add(lblResult);     
    cValue = celsiusField.getText();

    convertButton = new JButton("Convert");
    convertButton.setBounds(10, 39, 157, 23);
    contentPane.add(convertButton);
    convertButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int parsed = Integer.parseInt(cValue);
        }           
    });
}

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                CelsiusConverter frame = new CelsiusConverter();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

And this is the error:

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 learningWindowBuilder.CelsiusConverter$1.actionPerformed(CelsiusConverter.java:53)
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$500(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$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.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$JavaSecurityAccessImpl.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)

Solution

  • cValue = celsiusField.getText();
    

    You can't invoke that statement yet because the GUI isn't even visible and the user hasn't had a chance to enter data into the text field.

    You need to get the text from the text field in your ActionListener

    String cValue = celsiusField.getText();
    int parsed = Integer.parseInt(cValue);