Reputation: 205
Here's a picture of the interface of my program, just for simplicity when explaining my problem.
So the program starts with this screen, and the first step is to edit your name, by clicking the edit name button, which calls this method:
private void editName() {
NameLabel = new javax.swing.JLabel();
NameField = new javax.swing.JTextField();
Sumbit = new javax.swing.JButton();
Sumbit.addActionListener(this);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setAlwaysOnTop(true);
setType(java.awt.Window.Type.POPUP);
NameLabel.setText("Name:");
NameField.setText(name);
Sumbit.setText("Sumbit");
..location code..
So you type your name in the text field that pops up, and you hit submit. Then I get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at kraz.Kraz.game(Kraz.java:62)
at kraz.Kraz.actionPerformed(Kraz.java:186)
The actionPerformed on line 186 is the submit button:
else if (e.getSource() == Sumbit)
{
name = NameField.getText();
NameField.setText("" + name);
if (step == 1)
{
++step;
game();
}
}
Line 62 is where I call the game() method. The next one, line 162 is:
public void game() {
if (step == 1)
{
HealthBar.setValue(100);
}
else if (step == 2)
{
EventField.setText("Test");
ProgressBar.setValue(1);
}
}
and the error is when I set the text in EventField.
Full Code: http://pastebin.com/rBWju8vX
Upvotes: 1
Views: 498
Reputation: 347314
Call this()
in the second constructor:
public Kraz() {
initComponents();
setVisible(true);
game();
}
public Kraz(String check) {
this(); // <-- Add here
if (check.equals("editName"))
{
editName();
setVisible(true);
}
}
Upvotes: 0
Reputation: 143906
You have 2 constructors, one calls initComponents()
and the other doesn't:
public Kraz() {
initComponents();
setVisible(true);
game();
}
public Kraz(String check) {
if (check.equals("editName"))
{
editName();
setVisible(true);
}
}
In the main method, you call new Kraz();
which is the one that calls initComponents()
. But when you handle the EditName event, you call the constructor again but the other one, new Kraz("editName")
, which doesn't call initComponents()
so the EventField is null:
else if (e.getSource() == EditName)
{
new Kraz("editName");
}
So when, in this new instance of Kraz
, you hit the "Submit" button, the new instance handles the event and calls game()
, except none of the fields have been initialized.
Upvotes: 7