有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用户界面Java代码不工作(GUI)

我正在尝试制作一个gui,它接受一个数字并返回总和和平均值。我已经尝试过让它工作,但在cmd中使用java StatClacGui时,它会返回4个错误。以下是代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class StatCalcGUI extends JPanel implements ActionListener {
    double sumt = 0;
    double avg;
    int count =0;

    public static void main(String[] args) {
        JFrame window = new JFrame("Stat Calc");
        StatCalcGUI content = new StatCalcGUI();
        window.setContentPane(content);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLocation(120,70);
        window.setSize(450,350);
        window.setVisible(true);
    }

    private JTextField tekst;
    private JLabel entry;
    private JLabel sum;
    private JLabel average;
    private JLabel stddev;


    private JButton clearButton;
    private JButton enterButton;

    private JLabel titel;

    private StatCalcGUI stats;

    public StatCalcGUI(){
        setBackground(Color.BLACK);
        setLayout(new GridLayout(6,1));
        clearButton = new JButton("Clear");
        clearButton.addActionListener(this);
        enterButton = new JButton("Enter");
        enterButton.addActionListener(this);
        JPanel ip = new JPanel();
        ip.setLayout(new GridLayout(1,3));
        ip.add(tekst);
        ip.add(enterButton);
        ip.add(clearButton);

        titel =    makeLabel(" Enter a number in field");
        entry =    makeLabel(" Number of entries   "+ count);
        sum =      makeLabel(" Sum                 " + sumt);
        average =  makeLabel(" Average             " + avg);
        stddev =   makeLabel(" Standard Deviation  ");

        add(titel);
        add(ip);
        add(entry);
        add(sum);
        add(average);
        add(stddev);
    }

    public void actionPerformed(ActionEvent evt) {
        if (evt.getSource() == enterButton) {
            double add = Double.parseDouble(tekst.getText());
            sumt = sumt + add;
            count ++;
            avg =(double) sumt/count;

        }else if (evt.getSource() == clearButton) {
            sumt = 0;
            avg = 0;
            count = 0;
        }

    }
    private JLabel makeLabel(String teskt){
        JLabel label = new JLabel(teskt);
        label.setBackground(Color.RED );
        label.setForeground(Color.BLUE );
        label.setFont(new Font("Monospaced", Font.PLAIN, 12));
        label.setOpaque(true);
        return label;
    }
}

错误代码是:

Exception in thread "main" java.lang.NullPointerException
        at java.awt.Container.addImpl(Unknown Source)
        at java.awt.Container.add(Unknown Source)
        at StatCalcGUI.<init>(StatCalcGUI.java:43)
        at StatCalcGUI.main(StatCalcGUI.java:12)

我真的不明白这个错误,有人能帮忙吗


共 (1) 个答案

  1. # 1 楼答案

    你从不初始化tekst,所以它是空的,你会得到一个NullPointerException