这个 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
}
}
最佳答案
我强烈怀疑 NumberFormatException
正在被抛出。
毕竟,任何时候小程序尝试绘制自身 - 包括在初始化之后立即 - 您都将运行以下代码:
// 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);
所以当 txt1.getText()
返回一个空字符串,在用户有机会输入任何内容之前,您将解析该空字符串,这将抛出 NumberFormatException
.
我觉得这个小程序的整体设计不太合适。您为什么要使用drawString
标签本质上是什么?
我会添加一个或两个 Label
控件 - 一个用于完整文本“结果:”和结果,或者一个仅用于“结果:”和一个单独的结果。那么你不需要覆盖paint()
完全可以 - 您可以在文本框内容更改时添加处理程序 - 毕竟,这是您唯一需要更改任何内容的时间。
然后您应该输入 Integer.parseInt
调用 try/catch block ,捕获 NumberFormatException
。 (您也可以考虑使用 NumberFormat
而不是 Integer.parseInt
,但您可以稍后再这样做...)
关于Java Applet 编译得很好但无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12017004/