简体   繁体   English

Java Applet编译良好,但无法运行

[英]Java Applet compiles very well but does not run

What is wrong with this java Applet , even tho I compile it with no issue it does not run. 这个Java Applet有什么问题,即使我没有问题也不能编译它。

import java.applet.*;//Importing java.applet
public class MyApplet extends Applet {
   TextField txt1, txt2;
   public void init(){//Initializing our applet
       txt1 = new TextField(""); //Creates a textfield 'txt1'
       txt2 = new TextField(""); //Creates a textfield 'txt2'
       setBackground(Color.CYAN);//Setting background color to CYAN
       add(txt1); //Adds textfield 'txt1' to your applet
       add(txt2); //Adds textfield 'txt2' to your applet
   }
   public void paint(Graphics obj){//Paint method to display our message
       String s1 =  txt1.getText(); //Fetching data from text field 1.
       String s2 =  txt2.getText(); //Fetching data from text field 2.
       int num1=0, num2 = 0, num3;   //Declaring 3 integer variables    
       num1 = Integer.parseInt(s1); //Parsing the string value of text field 1 to integer
       num2 = Integer.parseInt(s2); //Parsing the string value of text field 2 in integer
       num3 = num1 + num2;       //Performing addition
       String s3 = String.valueOf(num3); //Converting the result from integer to string
       obj.drawString("Result:", 40, 50);
       obj.drawString(s3, 50, 50);//To display the result
   }
}

I strongly suspect a NumberFormatException is being thrown. 我强烈怀疑会引发NumberFormatException

After all, any time the applet tries to paint itself - including immediately after initialization - you'll be running this code: 毕竟, 无论何时小程序尝试进​​行自我绘制 (包括在初始化之后立即进行绘制) ,您都将运行以下代码:

// Comments removed as they were more distracting than useful. You really
// *don't* need to comment variable declarations to say they're declarations...
String s1 =  txt1.getText();
String s2 =  txt2.getText();
int num1=0, num2 = 0, num3; 
num1 = Integer.parseInt(s1);
num2 = Integer.parseInt(s2);

So when txt1.getText() returns an empty string, which it will before the user has had a chance to type anything, you're going to be parsing that empty string, which will throw a NumberFormatException . 因此,当txt1.getText()返回一个空字符串(将在用户有机会键入任何内容之前)时,您将解析该空字符串,这将引发NumberFormatException

It feels to me that the general design of this applet is inappropriate. 在我看来,此applet的总体设计不合适。 Why would you want to use drawString for what are essentially labels? 为什么要使用drawString作为本质上的标签?

I would add either one or two Label controls - either one for the complete text "Result: " and the result, or one for just "Result: " and a separate one for the result. 我将添加一个或两个Label控件-一个用于完整的文本“ Result:”和结果,或者一个仅用于“ Result:”,另一个用于结果。 Then you don't need to override paint() at all - you can instead add handlers for when the textbox contents change - which is, after all, the only time you need to change anything. 然后,您根本不需要重写paint() -您可以在文本框内容更改时添加处理程序-毕竟,这是您唯一需要更改的内容。

You should then put the Integer.parseInt call into a try/catch block, catching NumberFormatException . 然后,应将Integer.parseInt调用放入try / catch块中,以捕获NumberFormatException (You could also consider using a NumberFormat instead of Integer.parseInt , but you can do that later...) (您也可以考虑使用NumberFormat而不是Integer.parseInt ,但是稍后可以这样做...)

The major problem is the strings couldn't be painted properly. 主要的问题是字符串无法正确绘制。 The paint method calls by the applet several times before you have any input. 在您没有任何输入之前, paint方法将多次调用applet。 So, the textfields has empty strings. 因此,文本字段具有空字符串。 This because a NumberFormatException . 这是因为NumberFormatException Check the text for empty value. 检查文本是否为空值。 If you parse numbers add try/catch block. 如果您解析数字,请添加try/catch块。 In addition moving the logic to the method calculate with repaint and initiating it when you make input. 另外,将逻辑移到方法上使用repaint calculate ,并在输入时将其初始化。 This could be happen if you add some listeners to the textfields. 如果您在文本字段中添加一些侦听器,则可能会发生这种情况。

import java.applet.*;
import java.awt.*;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;//Importing java.applet
public class MyApplet extends Applet
{
  TextField txt1, txt2;
  String s3;
  public void init()//Initializing our applet
  {
    txt1 = new TextField(""); //Creates a textfield 'txt1'
    txt2 = new TextField(""); //Creates a textfield 'txt2'
    txt1.addTextListener(new TextListener(){
      public void textValueChanged(TextEvent e) {
        calculate();
      }
    });
    txt2.addTextListener(new TextListener(){
      public void textValueChanged(TextEvent e) {
        calculate();
      }
    });
    setBackground(Color.CYAN);//Setting background color to CYAN
    add(txt1); //Adds textfield 'txt1' to your applet
    add(txt2); //Adds textfield 'txt2' to your applet
  }

  void calculate(){
    try {
      String s1 =  txt1.getText(); //Fetching data from text field 1.
      String s2 =  txt2.getText(); //Fetching data from text field 2.
      int num1=0, num2 = 0, num3;  //Declaring 3 integer variables
      num1 = Integer.parseInt(s1); //Parsing the string value of text field 1 to integer
      num2 = Integer.parseInt(s2); //Parsing the string value of text field 2 in integer
      num3 = num1 + num2;          //Performing addition
      s3 = String.valueOf(num3); //Converting the result from integer to string
      repaint();
    } catch (NumberFormatException nfe){}

  }
  public void paint(Graphics obj)//Paint method to display our message
  {
    super.paint(obj);
    obj.drawString("Result:", 100, 100);
    if (s3 != null)
      obj.drawString(s3, 150, 100);//To display the result
  }
}

The problem is in : 问题出在:

txt1 = new TextField("");
txt2 = new TextField("");

as

String s1 =  txt1.getText(); 
String s2 =  txt2.getText();
num1 = Integer.parseInt(s1);
num2 = Integer.parseInt(s2);

will not be able to parse "" and will throw exception as explained by Jon Skeet. 如乔恩·斯凯特(Jon Skeet)所述,将无法解析""并会throw exception

So the fix could be a try catch block(Exception handling): 因此, 解决方法可以是try catch块(异常处理):

try{
    num1 = Integer.parseInt(s1);
    num2 = Integer.parseInt(s2);
   }catch(NumberFormatException ex){
       System.out.println(ex);
   }

OR have some initial parseable String value 或具有一些初始可解析的String

txt1 = new TextField("0"); 
txt2 = new TextField("0");

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

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