import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class StepOne extends Frame implements ActionListener
{
private Button enter, quit;
TextField wei,nwei;
public StepOne()
{
Panel pan= new Panel();
pan.add(new Label("地球上重量(牛):"));
TextField wei = new TextField(10);
wei.addActionListener(this);
pan.add(wei);
pan.add(new Label("月球上重量(牛):"));
TextField nwei = new TextField(10);
pan.add(nwei);
enter = new Button("计算");
enter.addActionListener(this);
pan.add(enter);
quit = new Button("退出");
quit.addActionListener(this);
pan.add(quit);
add(pan,"North");
setSize(800, 400);
validate();
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == quit)
System.exit(0);
else if (e.getSource() == enter)
{
double weight, nweight;
String s= wei.getText();
weight=Double.parseDouble(s);
WeightConverter converter =new WeightConverter();
converter.setExchangeRate(1.0/6.0);
nweight=converter.fromEarth(weight);
nwei.setText(nweight+"牛\n");
}
}
public static void main(String[] args)
{
(new StepOne()).setVisible(true);
}
}
class WeightConverter
{
private double exchangeRate;
public double fromEarth(double weight)
{
return ( weight*exchangeRate);
}
public void setExchangeRate(double rate)
{
exchangeRate=rate;
}
public double toEarth(double alienweight)
{
return (alienweight/exchangeRate);
}
}
一个体重转换的实例。编译没问题,运行后TextField区域没有显示结果?出现:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException的异常,这是什么问题啊?看过相应的api,未果。点播一下咯,:-)
[此贴子已经被作者于2007-5-18 13:09:07编辑过]