Jordan Skittaraps
Jordan Skittaraps

Reputation: 41

Java - num1 = event.getActionCommand() Doesn't work (Can't set the String as an Int)

I have tried looking for other obvious results, but for some reason when I added them, half of my program stopped working. Basically, I'm trying to get these two numbers input from the JTextField and add them together, however, I can't add two strings together. I've tried casting the results into integers, but conversion from String to Int is apparently impossible. I could be missing something clearly obvious, but I'm a beginner and I need some advice, thanks.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class GUI extends JFrame {
   private JTextField cmd = new JTextField(5);
   private JButton cancel = new JButton("Cancel");
   private JLabel Help = new JLabel("Enter First Number");
   private int num1;
   private int num2;
   private int ans = num1 + num2;

   public GUI() {
      super("Command Line - Sum");
      setLayout(new FlowLayout());
      System.out.println("Successfully opened sum window.");
      add(cmd);
      add(Help);
      add(cancel);
      cmdHandler handler = new cmdHandler();
      cmd.addActionListener(handler);
      cancel.addActionListener(handler);
   }

   public static void closeWindow() {
      GUI g = new GUI();
      g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      g.setSize(275, 180);
      g.setVisible(true);
      g.setResizable(false);
      g.setLocation(0, 550);
   }

   private class cmdHandler implements ActionListener {
      int a = 0;

      public void actionPerformed(ActionEvent event) {
         if (event.getSource().equals(cmd)) {
            if (a == 0) {
               cmd.setText("");
               a++;
               Help.setText("Enter Second Number");
            } else if (a == 1) {
               cmd.setText(num1 + " + " + num2 + " = " + ans);
               a++;
               Help.setText("Your final result is " + ans);
            } else if (a == 2) {
               closeWindow();
               GUI.this.dispose();
            }
         } else if (event.getSource().equals(cancel)) {
            closeWindow();
            GUI.this.dispose();
         }
      }
   }
}

Sorry for any duplicates, but I can't find any solutions to match my situation.

Upvotes: 1

Views: 460

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Don't cast but instead parse..

int number = Integer.parseInt(testString);

or

double doubleNumber = Double.parseDouble(testString);

For example,

  public void actionPerformed(ActionEvent event) {
     if (event.getSource().equals(cmd)) {
        int number = 0;
        try {
           number = Integer.parseInt(cmd.getText());
        } catch (NumberFormatException e) {
           // TODO: figure out what to do if bad input entered
        }

        // ..........

Notes

  • In your code, you calculate ans on program creation, but that won't work since the user has updated nothing yet. Thus the calculation needs to be done in the ActionListener itself, which should allow time for the user to first input data.
  • We often wrap the parsing above in a try/catch block and catch NumberFormatExceptions as this will allow us to find and respond to bad input, for instance non-numeric input.
  • Rather than swap views, why not simplify things greatly and create one window with two JTextFields, a calculate button, and an answer JLabel.

Upvotes: 3

Related Questions