[英]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.
基本上,我试图从JTextField获取这两个数字并将它们添加到一起,但是,我不能将两个字符串一起添加。 I've tried casting the results into integers, but conversion from String to Int is apparently impossible.
我已经尝试将结果转换为整数,但从String到Int的转换显然是不可能的。 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. 对不起任何重复,但我找不到符合我情况的解决方案。
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 笔记
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.