Reputation: 41
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
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
Upvotes: 3