Results 1 to 16 of 16
  1. #1
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default NullPointerException when use a method from another class

    at first sorry for my bad english
    if i have this class
    Java Code:
    public class A extends JFrame
    {
    JLabel lb_name=new JLabel("My Name");
    /////////
    the rest of the class code here
    ////////
    public void setLabelVs()
        {
            lb_name.setVisable(false);
        }
    }
    & i have this class
    Java Code:
    public class B extends JFrame
    {
          public static void main(String[] args) 
         {
              A obj = new A();
              obj.setLabelVs();
         }
    }
    this code will show this error
    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    on this line
    Java Code:
    obj.setLabelVs();
    i can't make a setter method for the JLabel & call it in another class
    please help
    Note : i made the B class is inner class and i face the same error , i made the object from class A in Class A and when i try to call the method i face the same error

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: NullPointerException when use a method from another class

    Your error is not in the code you've posted, but is elsewhere. Could you be shadowing the JLabel field by re-declaring it in A's constructor? This has been happening a lot here lately.

    for example, could you be doing this?

    Java Code:
    public class A extends JFrame {
       private JLabel lb_name; // this variable remains null
    
       A() {
          // because it is re-declared here:
          JLabel lb_name = new JLabel("My Name");
          add(lb_name);
       }
    
       public void setLabelVs() {
          lb_name.setVisible(false);
       }
    }
    Last edited by Fubarable; 10-30-2011 at 03:19 AM.

  3. #3
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default Re: NullPointerException when use a method from another class

    this the full code of the second class
    Java Code:
    public class B implements Runnable
    {
        A obj = new A();
        @Override
        public void run(){
            obj.lb_name.setText("My name");
        }
    }
    when i try to set the text direct from the B class always show the same error
    when i put this method in A class
    Java Code:
    public void setLabelVs()
        {
            lb_name.setVisable(false);
        }
    and make the B class like that
    Java Code:
    public class B implements Runnable
    {
        A obj = new A();
        @Override
        public void run(){
            obj.lb_name.setLabelVs();
        }
    }
    also it's show the same error
    even if B class is not a thread i face the same error :(
    how can i change JLabel text or visable or bounds from another class by making a object of A class

  4. #4
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default Re: NullPointerException when use a method from another class

    i wrote a replay but it doesn't show up !!!!

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: NullPointerException when use a method from another class

    You haven't shown the most important code: the full text of the "A" class.

  6. #6
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default Re: NullPointerException when use a method from another class

    Class A is along block of code
    i just picked up every thing related with the error

  7. #7
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default Re: NullPointerException when use a method from another class

    if it's ok i can post it but class A is 200 lines of code

  8. #8
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default Re: NullPointerException when use a method from another class

    that is the first class
    Java Code:
    package shooooot;
    import java.awt.Event;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    
    public class Shooooot extends JFrame
    {
        Shooooot gloObj;
        int num=0;
        JPanel panel_main;
        JLabel lb_score,lb_scorenum,lb_spaceimg,lb_tankimg,lb_bombimg,lb_backimg,lb_time,lb_timer;
        Thread th = new Thread();
        Shooooot()
        {
            JLabel lb_time = new JLabel("My Name");
            
        }
        public void instControls()
        {
            panel_main = new JPanel();
            lb_score = new JLabel("Score");
            lb_scorenum = new JLabel("0");
            lb_spaceimg = new JLabel(new ImageIcon(getClass().getResource("images/spaceship.png")));
            lb_tankimg = new JLabel(new ImageIcon(getClass().getResource("images/cannon.png")));
            lb_bombimg = new JLabel(new ImageIcon(getClass().getResource("images/bomb.png")));
            lb_backimg = new JLabel(new ImageIcon(getClass().getResource("images/back.jpg")));
            lb_time = new JLabel("Timer");
            lb_timer = new JLabel("0");
        }
        
        public void setControls()
        {
            panel_main.setBounds(0,0,getWidth(),getHeight());
            lb_backimg.setBounds(0,0,getWidth(),getHeight());
            lb_score.setBounds(450,5,50,20);
            lb_scorenum.setBounds(460,30,50,20);
            lb_spaceimg.setBounds(0,45,75,38);
            lb_tankimg.setBounds(220,410,60,90);
            lb_bombimg.setBounds(230,410,40,40);
            lb_bombimg.setVisible(false);
            lb_time.setBounds(0,5,50,20);
            lb_timer.setBounds(5,30,50,20);
        }
        
        public void addControls()
        {
            lb_backimg.add(lb_bombimg);
            lb_backimg.add(lb_score);
            lb_backimg.add(lb_scorenum);
            lb_backimg.add(lb_spaceimg);
            lb_backimg.add(lb_tankimg);
            lb_backimg.add(lb_time);
            lb_backimg.add(lb_timer);
            panel_main.add(lb_backimg);
            add(panel_main);
        }
        
        public void setContainer()
        {
            setLayout(null);
            setVisible(true);
            setTitle("Shoooot");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setResizable(false);
            setSize(500, 500);
            panel_main.setLayout(null);     
        }
        
        public void setAction()
        {
            addKeyListener(new doAction());
        }
        
        public void threadRuning()
        {
            int rorl=0;
            
            
              try{
                  
                  for(int i = 1;i>0;i++)
                  {
                        lb_timer.setText((String.valueOf((i))));
                        if(lb_spaceimg.getX()==424)
                        {
                            rorl=1;
                           // lb_spaceimg.setBounds((lb_spaceimg.getX()-1),45,75,38);
    
                        }else if(lb_spaceimg.getX()==1)
                        {
                            rorl=0;
                          //  lb_spaceimg.setBounds((lb_spaceimg.getX()+1),45,75,38);
                        }
    
                        if(rorl==0)
                        {
                            lb_spaceimg.setBounds((lb_spaceimg.getX()+1),45,75,38);
                        }
                        else if(rorl==1)
                        {
                            lb_spaceimg.setBounds((lb_spaceimg.getX()-1),45,75,38);
                        }
                        
                      /*  if((lb_bombimg.getY())<=430)
                          {
                              lb_bombimg.setVisible(true);
                              lb_bombimg.setBounds(230,(lb_bombimg.getY()-5),40,40);
                          }*/
    
                        th.sleep(10);
                    }
              }
              catch(InterruptedException tException){
                    tException.printStackTrace();
              }
        }
        
        public void shootBall() {
        
            lb_time.setText("");
            lb_bombimg.setVisible(true);
            lb_bombimg.setBounds(lb_bombimg.getX(),(lb_bombimg.getY()-10),lb_bombimg.getWidth(),lb_bombimg.getHeight());
           // setTitle(null);
        }
        
        public static void main(String[] args) 
        {
            Shooooot obj = new Shooooot();
            obj.instControls();
            obj.setContainer();
            obj.setControls();
            obj.addControls();
            obj.setAction();
           // obj.shoto.start();
            obj.threadRuning();
            
            
        }
        
        class doAction implements KeyListener
        {
            @Override
            public void keyTyped(KeyEvent ke)
            {
    
            }
            
            @Override
            public void keyPressed(KeyEvent ke)
            {
                if(ke.getKeyCode()==32)
                {
                   NewClass obo = new NewClass();
                   obo.run();
                    
                }
            }
            
            @Override
            public void keyReleased(KeyEvent ke)
            {
    
    
            }
        }
    }
    and this is the second class
    Java Code:
    package shooooot;
    public class NewClass implements Runnable
    {
        Shooooot obj = new Shooooot();
        @Override
        public void run(){
            obj.lb_score.setText("100");
        }
    }
    When you press (space key) on the keyboard you make an object from (NewClass) and run it cuz it's Thread
    in the Run method on this Thread you change the text of (lb_score) but it show
    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at shooooot.NewClass.run(NewClass.java:7)
    	at shooooot.Shooooot$doAction.keyPressed(Shooooot.java:159)
    	at java.awt.Component.processKeyEvent(Component.java:6161)
    	at java.awt.Component.processEvent(Component.java:5980)
    	at java.awt.Container.processEvent(Container.java:2105)
    	at java.awt.Window.processEvent(Window.java:1836)
    	at java.awt.Component.dispatchEventImpl(Component.java:4564)
    	at java.awt.Container.dispatchEventImpl(Container.java:2163)
    	at java.awt.Window.dispatchEventImpl(Window.java:2478)
    	at java.awt.Component.dispatchEvent(Component.java:4390)
    	at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1881)
    	at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:749)
    	at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1025)
    	at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:892)
    	at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:713)
    	at java.awt.Component.dispatchEventImpl(Component.java:4434)
    	at java.awt.Container.dispatchEventImpl(Container.java:2163)
    	at java.awt.Window.dispatchEventImpl(Window.java:2478)
    	at java.awt.Component.dispatchEvent(Component.java:4390)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:649)
    	at java.awt.EventQueue.access$000(EventQueue.java:96)
    	at java.awt.EventQueue$1.run(EventQueue.java:608)
    	at java.awt.EventQueue$1.run(EventQueue.java:606)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:116)
    	at java.awt.EventQueue$2.run(EventQueue.java:622)
    	at java.awt.EventQueue$2.run(EventQueue.java:620)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:619)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: NullPointerException when use a method from another class

    Yes, I think the forum software can handle 200 lines, but be sure to enclose them in code tags: the tag [code] goes above your code block and [/code] goes below the block. Note that the beginning and ending code tags are different and that these tags use square braces [ and ] not angled brackets < and >.

  10. #10
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default Re: NullPointerException when use a method from another class

    ok i posted it just approve the post
    thanks :)

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: NullPointerException when use a method from another class

    OK, so we know tha tlb_score is null when you feel it shouldn't be null. So first thing we do is look where you declare the variable, and you do so here:

    Java Code:
    public class Shooooot extends JFrame
    {
        Shooooot gloObj;
        int num=0;
        JPanel panel_main;
    
        // **** declared here ***
        JLabel lb_score,lb_scorenum,lb_spaceimg,lb_tankimg,lb_bombimg,lb_backimg,lb_time,lb_timer;
        Thread th = new Thread();

    Next we look at where you make the variable refer to a non-null object by passing it a valid JLabel (usually done by calling the JLabel constructor), and you do that here:

    Java Code:
        public void instControls()
        {
            panel_main = new JPanel();
            lb_score = new JLabel("Score"); // **** constructor called here
            // ... etc...
        }
    Next we look to see where you call the instControls method...

    And you in fact do this here in the main method that is in the Shooooot class:

    Java Code:
        public static void main(String[] args) 
        {
            Shooooot obj = new Shooooot();
            obj.instControls(); // **** here
            // ... etc ...
        }
    But, but, there's another main method where you also construct a Shooooot instance, and this is done in another class. So you must ask yourself, do you call the instControls, method on this Shooooot object? I'll bet not. Perhaps the instControls method should be in the Shooooot constructor so as to make it idiot-proof?

    Even more important than the solution for this specific problem is that you have to go through this or a similar process every time you run into a NullPointerException.

  12. #12
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default Re: NullPointerException when use a method from another class

    i put "instControls()" in Shooooot constructor
    and removed some of unused code , it's now look like that
    Java Code:
    package shooooot;
    import java.awt.Event;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    
    public class Shooooot extends JFrame
    {
        JPanel panel_main;
        JLabel lb_score,lb_scorenum,lb_spaceimg,lb_tankimg,lb_bombimg,lb_backimg,lb_time,lb_timer;
        Thread th = new Thread();
        Shooooot()
        {
            instControls();
            
        }
        public void instControls()
        {
            panel_main = new JPanel();
            lb_score = new JLabel("Score");
            lb_scorenum = new JLabel("0");
            lb_spaceimg = new JLabel(new ImageIcon(getClass().getResource("images/spaceship.png")));
            lb_tankimg = new JLabel(new ImageIcon(getClass().getResource("images/cannon.png")));
            lb_bombimg = new JLabel(new ImageIcon(getClass().getResource("images/bomb.png")));
            lb_backimg = new JLabel(new ImageIcon(getClass().getResource("images/back.jpg")));
            lb_time = new JLabel("Timer");
            lb_timer = new JLabel("0");
        }
        
        public void setControls()
        {
            panel_main.setBounds(0,0,getWidth(),getHeight());
            lb_backimg.setBounds(0,0,getWidth(),getHeight());
            lb_score.setBounds(450,5,50,20);
            lb_scorenum.setBounds(460,30,50,20);
            lb_spaceimg.setBounds(0,45,75,38);
            lb_tankimg.setBounds(220,410,60,90);
            lb_bombimg.setBounds(230,410,40,40);
            lb_bombimg.setVisible(false);
            lb_time.setBounds(0,5,50,20);
            lb_timer.setBounds(5,30,50,20);
        }
        
        public void addControls()
        {
            lb_backimg.add(lb_bombimg);
            lb_backimg.add(lb_score);
            lb_backimg.add(lb_scorenum);
            lb_backimg.add(lb_spaceimg);
            lb_backimg.add(lb_tankimg);
            lb_backimg.add(lb_time);
            lb_backimg.add(lb_timer);
            panel_main.add(lb_backimg);
            add(panel_main);
        }
        
        public void setContainer()
        {
            setLayout(null);
            setVisible(true);
            setTitle("Shoooot");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setResizable(false);
            setSize(500, 500);
            panel_main.setLayout(null);     
        }
        
        public void setAction()
        {
            addKeyListener(new doAction());
        }
        
        public void threadRuning()
        {
            int rorl=0;
            
            
              try{
                  
                  for(int i = 1;i>0;i++)
                  {
                        lb_timer.setText((String.valueOf((i))));
                        if(lb_spaceimg.getX()==424)
                        {
                            rorl=1;
                           // lb_spaceimg.setBounds((lb_spaceimg.getX()-1),45,75,38);
    
                        }else if(lb_spaceimg.getX()==1)
                        {
                            rorl=0;
                          //  lb_spaceimg.setBounds((lb_spaceimg.getX()+1),45,75,38);
                        }
    
                        if(rorl==0)
                        {
                            lb_spaceimg.setBounds((lb_spaceimg.getX()+1),45,75,38);
                        }
                        else if(rorl==1)
                        {
                            lb_spaceimg.setBounds((lb_spaceimg.getX()-1),45,75,38);
                        }
                        
                      /*  if((lb_bombimg.getY())<=430)
                          {
                              lb_bombimg.setVisible(true);
                              lb_bombimg.setBounds(230,(lb_bombimg.getY()-5),40,40);
                          }*/
    
                        th.sleep(10);
                    }
              }
              catch(InterruptedException tException){
                    tException.printStackTrace();
              }
        }
        
        public void shootBall() {
        
            lb_time.setText("");
            lb_bombimg.setVisible(true);
            lb_bombimg.setBounds(lb_bombimg.getX(),(lb_bombimg.getY()-10),lb_bombimg.getWidth(),lb_bombimg.getHeight());
           // setTitle(null);
        }
         
        public static void main(String[] args) 
        {
            Shooooot obj = new Shooooot();
            obj.instControls();
            obj.setContainer();
            obj.setControls();
            obj.addControls();
            obj.setAction();
           // obj.shoto.start();
            obj.threadRuning();
            
            
        }
        
        class doAction implements KeyListener
        {
            @Override
            public void keyTyped(KeyEvent ke)
            {
    
            }
            
            @Override
            public void keyPressed(KeyEvent ke)
            {
                if(ke.getKeyCode()==32)
                {
                   NewClass obo = new NewClass();
                   obo.run();
                    
                }
            }
            
            @Override
            public void keyReleased(KeyEvent ke)
            {
    
    
            }
        }
    }
    and the second class look like that
    Java Code:
    package shooooot;
    public class NewClass implements Runnable
    {
        Shooooot obj = new Shooooot();
        @Override
        public void run(){
            System.out.println(this.toString());
            obj.shootBall();
        }
    }
    but when i press space key this line work fine
    Java Code:
            System.out.println(this.toString());
    but this doesn't do anything
    Java Code:
    obj.shootBall();
    even if i replaced it with this
    Java Code:
    obj.lb_score.setText(null);
    it doesn't work
    i just need to access the JLabels from the second class

  13. #13
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default Re: NullPointerException when use a method from another class

    it doesn't work but it doesn't show any error

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: NullPointerException when use a method from another class

    You appear to have more methods that you need to put into your constructor.

  15. #15
    Trazan is offline Member
    Join Date
    Oct 2011
    Posts
    10
    Rep Power
    0

    Default Re: NullPointerException when use a method from another class

    if i put all the methods on the constructor
    Java Code:
    instControls();
            setContainer();
            setControls();
            addControls();
    it'll generate a new JFrame and it'll setText for the JLabel in the new JFrame
    sorry i am nope in java

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: NullPointerException when use a method from another class

    You're going to have to learn Java and do a little debugging. Keep at it as with time and practice and a little logic you'll get better. For instance if you see two JFrames then you must be creating two and setting both visible. Go through your code logically and with a debugger and you will figure it out.

Similar Threads

  1. Replies: 1
    Last Post: 10-17-2011, 01:00 AM
  2. Replies: 5
    Last Post: 01-26-2011, 06:38 PM
  3. Recursive Class throws NullPointerException
    By freeBatjko in forum New To Java
    Replies: 5
    Last Post: 11-03-2009, 09:18 AM
  4. Replies: 17
    Last Post: 07-12-2009, 06:42 PM
  5. another NullPointerException in LinkedList class
    By muffstuff in forum New To Java
    Replies: 7
    Last Post: 04-10-2009, 10:51 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
  •