开发者

Java Swing JSlider addChangeListener error

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜