0

I am getting the error: Exception in thread "main" java.lang.NullPointerException. I have looked at various questions with the same error, but fail to resolve my own. Because none of my objects are null and all my variables have been initialized, I cannot find where the issue lies. Here is the code

Main class:

package Myguipackage;

import javax.swing.JFrame;

public class mywindow {

    public static void main(String[] args) {
        Windowcontinued object = new Windowcontinued();
        object.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        object.setSize(500, 500);
        object.setVisible(true);
    }
}

Here is class Windowcontinued:

package Myguipackage;

import javax.swing.JOptionPane;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Windowcontinued extends JFrame {

    public JLabel text;
    public JTextField textfield;

    public Windowcontinued() {  //Constructor
        super("CHAT");
        setLayout(new FlowLayout());

        text = new JLabel("Would you like to talk to me?");
        add(text);
        text.setToolTipText("Please enter your answer");

        hear ear = new hear();

        textfield.addActionListener(ear);
        textfield = new JTextField("Yes or no? Erase this and type in your answer!");
        add(textfield);

    }

    class hear implements ActionListener {

        public void actionPerformed(ActionEvent event) {

            String string = "";

            if (event.getSource() == textfield)
                string = String.format("You typed in %s", event.getActionCommand());

            JOptionPane.showMessageDialog(null, string); //Open a new window that displays String string, which has changed based on which field you hit enter on.

        }
    }
}

Any help would be appreciated!

glw
  • 1,646
  • 1
  • 16
  • 20
Ruchir Baronia
  • 7,406
  • 5
  • 48
  • 83
  • 1
    You don't initialise the `textfield` before you use `addActionListener`, so it is `null`. You need to learn how to read the stack trace as most of the time, it will give you a good indication of where the problem originated from. From there you can put debug statements into your code and/or use a debugger to step through your code and inspect it's state – MadProgrammer Aug 13 '15 at 22:14
  • Could you provide the exception stacktrace? Just relevent lines okay? It would help our analyses. – Fernando Costa Aug 13 '15 at 22:15
  • Thank you MadProgrammer, it worked! I have one question though, how come there wasn't an error in eclipse? – Ruchir Baronia Aug 13 '15 at 22:16

0 Answers0