Results 1 to 18 of 18
  1. #1
    denno is offline Member
    Join Date
    Mar 2011
    Posts
    19
    Rep Power
    0

    Default NullPointerException Headache

    I've got a button that when pressed, will call a method in another java class, (a set method), to set a variable in an array. However, as the subject of this thread indicates, I keep getting the NullPointerException error.
    I've attached the code that is appropriate for the things being used, and would really love some help.

    Java Class 1 - ButtonPanel
    Java Code:
    class ButtonPanel extends JPanel{
      private Elevator elevator;
      public JButton b[] = new JButton[8];  // 8 Buttons
      public boolean bp[] = new boolean[8]; // the state of each button, pressed or not
      //constructor
      public ButtonPanel(Elevator elevator) {
        this.elevator = elevator;
        this.setLayout(new GridLayout(8,1));
        for(int i = 7 ; i >= 0 ; i--){
            b[i] = new JButton("F" + Integer.toString(i+1));
            b[i].setBackground(Color.LIGHT_GRAY);
            this.add(b[i]);
            b[i].addActionListener(new ButtonListener());
        }
      }
    
    
    class ButtonListener implements ActionListener{
    
        public void actionPerformed(ActionEvent e) {
            for(int i = 7 ; i >= 0 ; i--){
                if(e.getSource() == b[i]){
                    int j = i + 1;
                    System.out.println("Pressed Floor "+ j );
                    b[i].setBackground(Color.YELLOW);
                    elevator.setFloor(j);
                }
            }
        }
    
    }
    }
    Java Class 2 - Elevator
    Java Code:
     public void setFloor(int i){
          bp[i] = true;
          System.out.println("Marker");
      }
    It doesn't seem to matter what's actually inside the setFloor method, as the NullPointerException is thrown inside the actionPerformed method of the button action, when setFloor() is called..

    Anyone have any ideas? If you want more code then let me know...

    Thanks
    Denno

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I believe the problem is in your action listener. Do you intend every button click to loop through from 7 - 0? What happens if you remove the loop and use an instance variable and a constructor?

    Java Code:
    public class ButtonListener implements ActionListener{
      private int j;
      public ButtonListener(int j){
        this.j = j;
      }
      public void actionPerformed(ActionEvent e){
        System.out.println("Pressed floor " + j);
        b[j].setBackgroung(Color.YELLOW);
        elevator.setFloot(j);
      }
    }
    I suspect that when you add the listener to the button it also sets the color of every other button(some of which may not be initialized at the time)

    If this doesn't help you, it would be helpful if you gave us the EXACT error message, the line number and exact details help us out a good amount.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default

    Post the EXACT error message and indicate on which line it occurs.

  4. #4
    denno is offline Member
    Join Date
    Mar 2011
    Posts
    19
    Rep Power
    0

    Default

    The purpose of the for loop is to loop through each of the numbers in the array, until a match is found.. So it will only change the colour of the one button that is actually pressed, that bit is ok..

    As per your request, the exact error message is:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at elevator.ButtonPanel$ButtonListener.actionPerforme d(ButtonPanel.java:35)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.jav a:6267)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3267)
    at java.awt.Component.processEvent(Component.java:603 2)
    at java.awt.Container.processEvent(Container.java:204 1)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4630)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2099)
    at java.awt.Component.dispatchEvent(Component.java:44 60)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4577)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4238)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2478 )
    at java.awt.Component.dispatchEvent(Component.java:44 60)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 599)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122).

    Line 35 corresponds to the line:
    elevator.setFloor(j);

    I can run the program, and it will run perfectly, until I press the button.. However the program still runs, the animation still occurs (which is that of an elevator going up and then down)..

    Denno

  5. #5
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default

    The only thing on that line that can be null is elevator. Have you posted the correct code? Have you saved and compiled the correct version of the code? Do you have another constructor which does not initialise the elevator variable?

  6. #6
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default

    Another thought, maybe you are passing null to the ButtonPanel constructor.

  7. #7
    denno is offline Member
    Join Date
    Mar 2011
    Posts
    19
    Rep Power
    0

    Default

    I have pasted the correct code for the ButtonPanel class, and it compiled and ran and everything (using netbeans).

    Here is the whole of the Elevator class for consideration:
    Java Code:
    class Elevator extends JPanel{
      //Declaration of variables
      //private Elevator_Simulation app; //the Elevator Simulation frame
      private boolean up = false; // the elevator is moving up or down
      private int width;  // Elevator width
      private int height; // Elevator height
      private int xco;    // The x coordinate of the elevator's upper left corner
      private int space;  //The height of each floor (space between lines)
      private int yco;    // The y coordinate of the elevator's upper left corner
      private int dy0 = 3;    // Moving interval
      private int topy;   //the y coordinate of the top level
      private int bottomy;// the y coordinate of the bottom level
      private int panelHeight, panelWidth;
      TimeClass tc = new TimeClass();
      private Timer timer = new Timer(100, tc);   //the timer to drive the elevator movement
      public boolean bp[] = new boolean[9];
      private boolean start = true;
      private int delayCount;   //Keep track of the delay whilst the elevator is paused on a floor
    
    
      //constructor
      public Elevator() {
      //necessary initialization
          setBackground(Color.green);
          timer.start();
          //For Debugging
          //System.out.println("" + yco);
      }
    
      public void setFloor(int i){
          bp[i] = true;
          System.out.println("Marker");
      }
    
      public void unsetFloor(int i){
          bp[i] = false;
      }
    
      public int findFloor(){
          if(yco < space){
              return 8;
          }else if(yco > space && yco < 2*space){
              return 7;
          }else if(yco > 2*space && yco < 3*space){
              return 6;
          }else if(yco > 3*space && yco < 4*space){
              return 5;
          }else if(yco > 4*space && yco < 5*space){
              return 4;
          }else if(yco > 5*space && yco < 6*space){
              return 3;
          }else if(yco > 6*space && yco < 7*space){
              return 2;
          }else if(yco > 7*space){
              return 1;
          }else{
              return 0;     //will never get to this point
          }
      }
      // Paint elevator area
        @Override
      public void paintComponent(Graphics g) {
            panelHeight = getHeight();
            panelWidth = getWidth();
    
            super.paintComponent(g);
    
        //Horizontal Lines
            space = panelHeight / 8;
            g.drawLine(0, 0, panelWidth, 0);
            g.drawLine(0, space, panelWidth, space);
            g.drawLine(0, space*2, panelWidth, space*2);
            g.drawLine(0, space*3, panelWidth, space*3);
            g.drawLine(0, space*4, panelWidth, space*4);
            g.drawLine(0, space*5, panelWidth, space*5);
            g.drawLine(0, space*6, panelWidth, space*6);
            g.drawLine(0, space*7, panelWidth, space*7);
            g.drawLine(0, space*8, panelWidth, space*8);
        //End Horizontal Lines
    
        //Elevator
            int padding = (int) (panelWidth * 0.05);
            width = panelWidth - (2*padding);
            height = space-1;
            if(start){                                                              //only run this once
                yco = space * 7;                                                    //making the elevator start at floor 1
                start = false;
            }
            g.setColor(Color.LIGHT_GRAY);
            g.fillRect(padding, yco, width, height);
            g.setColor(Color.BLACK);
            g.drawLine(width/2, yco, width/2, yco + height);
        //End Elevator
      }
    
      //Handle the timer events
      public class TimeClass implements ActionListener {
            public void actionPerformed(ActionEvent tc){
                if(delayCount > 20){
                    delayCount--;
                }else{
                if(up){
                    yco = yco - dy0;                                                //Make the movement
                    if(yco < 0){                                                    //check if the elevator is at the top floor
                        up = false;                                                 //reverse the direction
                    }
                    if(bp[findFloor()]){
                        delayCount = 20;
                        System.out.println("Delay Set");
                    }
                }else{
                    yco = yco + dy0;                                                //make the movement
                    if(yco > panelHeight - height){                                 //check if the elevator is at the bottom floor
                        up = true;                                                  //reverse the direction
                    }
                }
                repaint();
            }
          }//End actionPerformed
        }//End of TimeClass
    }
    To be honest, I'm not really understand what I'm doing with the elevator part, I have just been looking through as many examples as I could find until I got something to work :S..

    Thanks for helping :)

  8. #8
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default

    Where is the code that creates the ButtonPanel?

  9. #9
    denno is offline Member
    Join Date
    Mar 2011
    Posts
    19
    Rep Power
    0

    Default

    I have found the problem!!

    Your second thought saying that I might passing null to ButtonPanel made me look in the top most java class. I was infact passing it elevator correctly, however I hadn't actually created the elevator, I had only made it ready to be created.. Which doesn't make sense... Here is what I mean:
    Java Code:
    private Elevator elevator;
    ...
    ...
    control = new ButtonPanel(elevator);
    ...
    ...
    ...
    elevator = new Elevator();
    So as you can see, I didn't actually properly create the object until after I tried to pass it to ButtonPanel :S.

    Thanks for your help though! I don't think I would have ever looked there for the answer.

    Thanks
    Denno

  10. #10
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default

    Wow, after all these years my crystal ball finally worked. ;)

  11. #11
    denno is offline Member
    Join Date
    Mar 2011
    Posts
    19
    Rep Power
    0

    Default

    While I've got your attention, and I've already posted the code in previous posts, can I ask another question?

    When a button is pressed, I change the colour of it to indicate the press, however when the elevator has stopped on the floor and moved on, I need the colour of the button to change back to where it was, and I'm not sure how to do that.
    I don't know how to access the elements in the ButtonPanel class from the Elevator class.. Do you know what I should do?
    If it's not a simple answer then it's ok if you don't take it on, but I was hoping there is something simple I need to do, or an example I can follow :).

    Thanks,
    Denno

  12. #12
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    How I would do it is to give the elevator class a reference to the button Panel and use getters and setters to access the buttons. However; I don't know for sure since I don't really know all of the code.

  13. #13
    denno is offline Member
    Join Date
    Mar 2011
    Posts
    19
    Rep Power
    0

    Default

    How do I go about giving a reference? The setters and getters I understand, but actually making the links between the two files is where I fail...

  14. #14
    denno is offline Member
    Join Date
    Mar 2011
    Posts
    19
    Rep Power
    0

    Default

    And if it makes it easier, here is the third and final class that I'm using in my project.
    Java Code:
    public class Elevator_Simulation extends JFrame{
      public JLabel state; // display the state of the elevator
      private JLabel id;  //your name and group
      public ButtonPanel control; //the button control panel
      private Elevator elevator = new Elevator(); // the elevator area
      public JPanel elevatorInfoPanel;
    
      //constructor
      public Elevator_Simulation() {
        JFrame frame = new JFrame("Elevator");
        frame.setLayout(new BorderLayout());
        frame.setSize(503,420);
        frame.setMinimumSize(new Dimension(503,420));
        frame.setVisible(true);
        
    //exit the program upon closing
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //set the window to start in the centre of the screen
        frame.setLocationRelativeTo(null);
        state = new JLabel("On");
    //Build the info panel with name and class
        JPanel buildInfo = new JPanel();
        JLabel info = new JLabel("Name: Luke Denton");
        buildInfo.add(info);
        frame.add(buildInfo, BorderLayout.NORTH);
    //Build the buttons panel
        control = new ButtonPanel(elevator);
        frame.add(control, BorderLayout.WEST);
    //Build the speed panel
        JPanel speedPanel = new JPanel(new GridLayout(1,1));
        JSlider speed = new JSlider(JSlider.VERTICAL, 2, 20, 8);
        speed.setMajorTickSpacing(2);
        speed.setMinorTickSpacing(1);
        speed.setPaintTicks(true);
        speed.setPaintLabels(true);
        speedPanel.add(speed);
        frame.add(speedPanel, BorderLayout.EAST);
    //Build the panel holding the current action of the elevator
        elevatorInfoPanel = new JPanel();
        JLabel elevatorInfo = new JLabel("The elevator is doing jack shit");
        elevatorInfoPanel.add(elevatorInfo);
        frame.add(elevatorInfoPanel, BorderLayout.SOUTH);
    //Build the centre part holding the elevator
        //elevator = new Elevator();
        frame.add(elevator, BorderLayout.CENTER);
    
        frame.pack();
      }
    
      // Main method
      public static void main(String[] args) {
    
      }
    
    }
    Denno

  15. #15
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    An example I can give is this, I am working on a text editor currently and I wanted to remove the action listeners from the main source file and have a file for each Action, and a file for the actual text editor.

    I gave each action a instance variable of type TextEditor and the constructor sets it up. With this I was able to manipulate the text editor stuff from inside the action classes.

    Java Code:
    public class TextEditor{
      private JButton button = new JButton("Do stuff");
      private JLabel label = new JLabel("H");
      public JLabel getLabel(){
        return label;
      }
      public void go(){
        JFrame frame = new JFrame()
        button.addActionListener(new RandomAction(this));
        frame.add(button);
        frame.add(label);
        frame.setVisible(true);
        frame.pack();
      }
      public static void main(String[] args){
        new TextEditor().go();
      }
    }
    
    public class RandomAction extends AbstractAction{
      private TextEditor theTextEditor;
      public RandomAction(TextEditor theTextEditor){
        this.theTextEditor = theTextEditor;
      }
      public void actionPerformed(ActionEvent e){
        Random rand = new Random();
        theTextEditor.getLabel().setText(rand.nextInt(50) + "");
      }
    }
    This allows you to click a button and change the label. The action listener takes a reference to the class TextEditor and uses it for manipulating the items in the text editor.
    Last edited by sunde887; 04-05-2011 at 07:51 AM.

  16. #16
    denno is offline Member
    Join Date
    Mar 2011
    Posts
    19
    Rep Power
    0

    Default

    I'm trying my best to adapt your example to my code, but I'm struggling big time..
    I have button listeners already set up, which is the ButtonListener class (in the code in previous posts, I've pasted it with the ButtonPanel class code). This ButtonListener code then tells the Elevator class which floor to stop at.. In the Elevator class there is a timer class which does all the movement stuff.
    If it's not too much trouble, do you think you could use my code to show me what to do? I'm really sorry to ask, and I really dislike when people ask on forums for other people to do their homework, but I'm otherwise not going to get it, I don't think :(..


    Actually, I've just had a thought.. what if I scrap the ButtonListener class, and instead use the Elevator class to implement the ActionListener.. Would that help?

  17. #17
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    The reason I gave you an example from something similar to my code is because it's a lot more basic. Ill have to read through your code a bit and see if I can come up with something.

    In the method that changes the color of the button when pushed, is it suitable to just sleep for a bit and then change it again?

  18. #18
    denno is offline Member
    Join Date
    Mar 2011
    Posts
    19
    Rep Power
    0

Similar Threads

  1. Modulo Headache
    By House in forum New To Java
    Replies: 17
    Last Post: 09-01-2010, 03:29 AM
  2. NullPointerException
    By Juuno in forum New To Java
    Replies: 1
    Last Post: 02-11-2010, 05:43 PM
  3. NullPointerException help?
    By fab5freddy in forum New To Java
    Replies: 2
    Last Post: 02-04-2010, 08:26 PM
  4. NullPointerException help me!
    By phancuong87 in forum New To Java
    Replies: 4
    Last Post: 01-19-2010, 04:01 PM
  5. Event headache
    By kammenos in forum Java Applets
    Replies: 2
    Last Post: 12-12-2008, 11:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •