Reputation: 19
I am creating a body mass index calculator to practice creating a GUI. However, I cannot figure out why I am getting the error shown below. I'm thinking that I'm trying to display the value of BMI incorrectly. Can someone help please?
Exception in thread "main" java.lang.NullPointerException at Source.(Source.java:21) at Main.main(Main.java:5)
import javax.swing.JFrame;
public class Main {
public static void main (String args []) {
Source sourceObject = new Source();
sourceObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sourceObject.setSize(275,180);
sourceObject.setVisible(true);
}
}
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Source extends JFrame {
private JLabel item1;
private JLabel item2;
private JLabel item3;
private String weight, height;
private int BMI;
public Source () {
super("Title");
setLayout(new FlowLayout());
item1 = new JLabel("Text");
item1.setToolTipText("This appears on hover");
weight = JOptionPane.showInputDialog(null, "Weight: ");
height = JOptionPane.showInputDialog(null, "Height: ");
item3.setText(String.valueOf(BMI));
add(item1);
add(item2);
add(item3);
}
int BMICalc() {
int weig = Integer.parseInt(weight);
int heig = Integer.parseInt(height);
int BMI = (weig)/(heig * heig);
return BMI;
}
}
Upvotes: 0
Views: 241
Reputation: 114807
You missed to create the JLabels 2 and 3. Try this:
public Source () {
super("Title");
setLayout(new FlowLayout());
item1 = new JLabel("Text");
item1.setToolTipText("This appears on hover");
item2 = new JLabel("Text");
weight = JOptionPane.showInputDialog(null, "Weight: ");
height = JOptionPane.showInputDialog(null, "Height: ");
BMICalc();
item3 = new JLabel("Text");
item3.setText(String.valueOf(BMI));
add(item1);
add(item2);
add(item3);
}
Upvotes: 0
Reputation: 131456
Actually item2
and item3
are declared but never instantiated.
But the actual problem is you are calling a method on item3
.
Instantiate all the fields that have a known value in the Source
constructor.
Upvotes: 1