简体   繁体   English

Java - num1 = event.getActionCommand()不起作用(不能将String设置为Int)

[英]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 笔记

  • In your code, you calculate ans on program creation, but that won't work since the user has updated nothing yet. 在您的代码中,您在程序创建时计算ans,但由于用户尚未更新任何内容,因此无法使用。 Thus the calculation needs to be done in the ActionListener itself, which should allow time for the user to first input data. 因此,计算需要在ActionListener本身中完成,这应该允许用户有时间首先输入数据。
  • 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. 我们经常将上面的解析包装在try / catch块中并捕获NumberFormatExceptions,因为这将允许我们查找并响应错误的输入,例如非数字输入。
  • Rather than swap views, why not simplify things greatly and create one window with two JTextFields, a calculate button, and an answer JLabel. 而不是交换视图,为什么不大大简化事情并创建一个窗口,其中包含两个JTextField,一个计算按钮和一个答案JLabel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM