gpt4 book ai didi

java applet 无法打印 actionPerformed 中的值

转载 作者:行者123 更新时间:2023-12-01 13:14:51 24 4
gpt4 key购买 nike

我的程序不会将我在操作执行方法中计算出的平均值打印到 GUI。我无法让它返回平均值。我已经尝试了我能想到的一切。另外,我对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. 您从未初始化 avgField,这会在您尝试将其添加到小程序时在 init 中导致 NullPointerException
  2. 你永远不会将平均值的结果分配给任何东西......

例如...

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

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

AWT 已经严重过时了...

关于java applet 无法打印 actionPerformed 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22549261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com