- Java code
import java.applet.Applet;import java.awt.BorderLayout;import java.awt.Choice;import java.awt.GridLayout;import java.awt.Panel;import java.awt.TextField;public class Calculation extends Applet { TextField t1 = new TextField ( "", 7 ); TextField t2 = new TextField ( "", 7 ); TextField t3 = new TextField ( "", 14 ); public void init () { setLayout ( new BorderLayout ( ) ); Panel p = new Panel ( ); add ( "North", p ); p.setLayout ( new GridLayout ( 1 , 2 ) ); p.add ( t1 ); p.add ( t2 ); Choice ch; ch = new Choice (); ch.addItem("+"); ch.addItem("-"); ch.addItem("*"); ch.addItem("/"); add ( "Center", ch ); add ( "South", t3 ); ch.addItemListener ( new LL ( )); }}import java.awt.TextField;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;public class LL implements ItemListener { public void itemStateChanged ( ItemEvent ie ) { TextField t1 = new TextField ( "", 7 ); TextField t2 = new TextField ( "", 7 ); TextField t3 = new TextField ( "", 14 ); if ( ie.getStateChange () == ItemEvent.SELECTED ) { String S = (String)ie.getItem (); String S1, S2, S3 = null; int num1, num2; S1 = t1.getText(); num1 = Integer.parseInt(S1); S2 = t2.getText(); num2 = Integer.parseInt(S2); if ( S.equals( "+" )) S3 = String.valueOf( num1 + num2 ); else if ( S.equals( "-" ) ) S3 = String.valueOf ( num1 - num2 ); else if ( S.equals ( "*" ) ) S3 = String.valueOf ( num1 * num2 ); else if ( S.equals ( "/" ) ) S3 = String.valueOf ( num1 / num2 ); t3.setText( S3 ); } } }
昨天学习了JFrame,这是参照书上写的一个小型计算器。
左右两边各有两个TextField,输入数字之后选择中间的计算方法(加减乘除),然后在最底下的TextField显示结果。
这是按照书上的一个类似程序写的,然后自己又加了点东西。
可以运行出界面,但一选择符号就提示出错。
请问问题出在哪里?最好帮忙修改下。十分感谢!
------解决方案--------------------
S1 = t1.getText();
这句 s1是"",所以下面
num1 = Integer.parseInt(S1);
没办法转成Integer
因为TextField t1 = new TextField ( "", 7 );
所以t1的值是空的
------解决方案--------------------
就像2楼说的,t1,t2是空。下面改写你的代码可以试试。
//import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculation extends JFrame implements ItemListener{
JTextField t1 = new JTextField( "1", 7 );
JTextField t2 = new JTextField( "1", 7 );
JTextField t3 = new JTextField( "", 14 );
public Calculation () {
setSize(200,200);
setTitle("Calculation");
JPanel p = new JPanel( );
p.setLayout(new FlowLayout( ));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//p.setLayout ( new GridLayout ( 1 , 4 ) );
p.add(t1);
p.add(t2);
Choice ch;
ch = new Choice();
ch.addItem("+");
ch.addItem("-");
ch.addItem("*");
ch.addItem("/");
p.add( "Center", ch );
p.add( "South", t3 );
ch.addItemListener( this);
setContentPane(p);
// show();
}
public static void main(String[] arguments){
Calculation cal=new Calculation();
cal.show();
}
//import java.awt.TextField;