java applet无法从actionPerformed打印值

时间:2014-03-21 02:52:18

标签: java applet actionlistener

我的程序不会将我在动作执行方法中计算出的平均值打印到GUI.I不能让它返回平均值。我已经尝试了我能想到的一切。另外,我是java的新手。请详细说明。谢谢!

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class blooddriveaverage extends Applet implements ActionListener 
{
 public void init() 
 {
   Label title = new Label("Blood Drive!");
  setBackground(Color.red);
  Label label1 = new Label("Department 1 amount: ");

  textField1 = new TextField(" ");

  avg = new Button("Average");
  clear = new Button ("Clear Fields");
  avg.addActionListener(this);
  clear.addActionListener(this);

  Label label2 = new Label("Department 2 amount: ");
  textField2 = new TextField(" ");
  Label label3 = new Label("Department 3 amount: ");
  textField3 = new TextField(" ");
  Label label4 = new Label("Department 4 amount: ");
  textField4 = new TextField(" ");

  add(title);
  add(label1);
  add(textField1);
  add(label2);
  add(textField2);
  add(label3);
  add(textField3);
  add(label4);
  add(textField4);
  add(avg);
  add(clear);
  add(avgField);
  avg.setBackground(Color.white);
  clear.setBackground(Color.orange);

 }
  public void actionPerformed(ActionEvent e) 
  {
    double average = 0;
   setLayout(new FlowLayout()); 
   int[] myarray = new int[4];
   myarray[0] = Integer.parseInt(textField1.getText().trim());
   myarray[1] = Integer.parseInt(textField2.getText().trim());
   myarray[2] = Integer.parseInt(textField3.getText().trim());
   myarray[3] = Integer.parseInt(textField4.getText().trim());
   if (e.getSource() == avg)
   {
     for(int i = 0; i < myarray.length; i++)
     {
       average += myarray[i];
     }
     average /= 4.00;



   }

   else
   {
    textField1.setText("");
    textField2.setText("");
    textField3.setText("");  
    textField4.setText("");
   }
 }

 TextField textField1, textField2, textField3, textField4, avgField;
 Button avg;
 Button clear;

}

1 个答案:

答案 0 :(得分:1)

  1. 当您尝试将avgField添加到小程序时,您永远不会初始化NullPointerException init
  2. 您永远不会将average的结果分配给任何内容......
  3. 例如......

    avgField.setText(NumberFormat.getNumberInstance().format(average));
    

    您可能想看看Code Conventions for the Java Programming LanguageCreating a GUI With JFC/Swing,如果您真的想要走在前沿,JavaFX

    AWT严重过时了......