views:

29

answers:

1

Hello,

I am using Swing to make a simple GUI but when I add a change listener to a JSlider, I get the following runtime error:

Exception in thread "main" java.lang.NullPointerException
        at XMovePanel.<init>(XMovePanel.java:15)

My code is the following:

public class XMovePanel extends JPanel
{
    JSlider xCoord;
    private GUIApp d;
    private XMoveListener xmove;

    public XMovePanel(GUIApp d)
    {
    this.d = d;
    xmove = new XMoveListener();

    // Error occurs here:
    xCoord.addChangeListener(xmove);

        // Settings for the slider
  private class XMoveListener implements ChangeListener{
@Override
        public void stateChanged(ChangeEvent event){

        // Change listener does stuff on action here

But I don't know why I would get an error when I add the change listener. What am I doing wrong?

+1  A: 

It looks like xCoord is null; try this instead:

JSlider xCoord = new JSlider();

Addendum: Because xCoord is an instance variable and it is meant to reference a JSlider, JLS 4.12.5 Initial Values of Variables specifies that "the default value is null." Trying to invoke a method on a null reference throws a NullPointerException.

trashgod
Thanks, silly me, I saw I tried to add the listener *before* I made the JSlider
Jonno_FTW
I've done the same thing. At least Java throws an exception, rather than silently dereferencing memory address zero!
trashgod