I am trying to make a gui that takes a number and returns the sum and avg. I have tried to make it work but it returns 4 errors when useing the java StatClacGui in cmd. Here is the code:
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;
}
}
And the error code is:
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)
I Dont really understand the error, can anybody help?
答案 0 :(得分:1)
You never initialize tekst
so it is null and you get a NullPointerException.