1

Can anyone tell me why the following code is throwing a null pointer exception? The exception is thrown at the line numberJTextField.addMouseListener(new MyMouseAdapter(numberJTextField)); in the class InputJFrame1.java.

import java.awt.*;

public class InputJFrame1 extends javax.swing.JFrame
{
    private javax.swing.JTextField numberJTextField;

    public InputJFrame1()
    {     
         numberJTextField.addMouseListener(new MyMouseAdapter(numberJTextField));
    }

    private void initComponents() 
    {
        numberJTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        getContentPane().add(numberJTextField);
    }

    public static void main(String args[])
    {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(InputJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(InputJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(InputJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(InputJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable()
                                    {
                                        @Override
                                        public void run()
                                        {
                                            new InputJFrame1().setVisible(true);
                                        }
                                    });
    }
}



import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTextField;

public class MyMouseAdapter extends MouseAdapter
{
    private JTextField jTextField;

    MyMouseAdapter(JTextField jTextField)
    {
        this.jTextField=jTextField;
    }

    @Override
    public void mouseClicked(MouseEvent e)
    {
          jTextField.setForeground(Color.red);
    }
}

Stacktrace:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at javaapplication8.InputJFrame1.(InputJFrame1.java:9) at javaapplication8.InputJFrame1$1.run(InputJFrame1.java:73) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:688) at java.awt.EventQueue$3.run(EventQueue.java:686) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:697) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

1
  • 1
    Please attach stacktrace Commented Jul 15, 2013 at 9:48

5 Answers 5

4

Don't remove the initComponents from the constructor. It makes sure that all components are properly initialized before using them, so it should be the first line of your constructor.

public InputJFrame1()
{     
     initComponents();
     numberJTextField.addMouseListener(new MyMouseAdapter(numberJTextField));
}
Sign up to request clarification or add additional context in comments.

Comments

2

I think you're forget to initialize numberJTextField (and Other Components) on default constructor

public InputJFrame1()
    {     
         initComponents();
         numberJTextField.addMouseListener(new MyMouseAdapter(numberJTextField));
    }

1 Comment

Thank you. That was the problem. :)
2

The field numberJTextField has not been assigned at the time the constructor is called. Try calling the initComponents method in the constructor, prior to adding the MouseListener.

public class InputJFrame1 extends javax.swing.JFrame
{
    private javax.swing.JTextField numberJTextField;

    public InputJFrame1()
    {     
         initComponents(); //Init components before using textfield
         numberJTextField.addMouseListener(new MyMouseAdapter(numberJTextField));
    }

    private void initComponents() 
    {
        numberJTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        getContentPane().add(numberJTextField);
    }

1 Comment

Or why set the listener in the constructor at all? Move the listener to initComponents() - where it belongs with the rest.
1
public InputJFrame1() {
        numberJTextField.addMouseListener(new MyMouseAdapter(numberJTextField));
    }

numberJTextField is null thats why.

1 Comment

Yes I had forgotten to initialize the components. Thank you. :)
0

You're instantiating a new InputJFrame1, but not calling your initialisation method, meaning numberJTextField is null.

I would put your initialisation code within your constructor. You can then mark the appropriate fields as final, and the compiler will tell you if you forget to initialise them.

private final javax.swing.JTextField numberJTextField;

Using final is a great way to avoid such initialisation problems in the future.

1 Comment

Thanks for the advice. Will follow it. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.