Skip to content
Advertisement

Calling a Method in a running Thread Object [closed]

I’m a Java beginner. I want to call a Method in a running Java Thread Object. It always throws this exception:

Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException: Cannot invoke “Graphic_handler.next()” because “this.this$0.grap” is null

public class Graphic_handler extends Thread {

    int off = 0;


    int columns = 7;
    int rows = 7;
    public Graphic_handler(Instagram_bot bot) {
    }

         

    public void run() {
   
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                //TODO: handle exception
            }
            set_time();
        }

    }


    private void set_time() {
        Date date = Calendar.getInstance().getTime();
        DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy    hh:mm:ss");
        String strDate = dateFormat.format(date);
        bot.date.setText(strDate);

    }

    public void change_center(int offset) {
    }

    public synchronized void next() {
        off++;
        notify();
    }

    public synchronized void last() {
        off--;
        notify();
    }
}

(Code is simplified)

Here is the part of the Code where I call the Method:

ActionListener right_ear = new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        grap.next();
    };
};
ActionListener left_ear = new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        grap.last();
    };
};


public static void main(String[] args) {

    Graphic_handler grap = new Graphic_handler(bot);
    grap.start();
    
}

Im trying to call the Methods next() and last() here.

Advertisement

Answer

What’s going on is you have a local variable that is hiding the instance variable.

class SomeClass {

   Graphic_handler grap;

   public static void main(String[] args) {
      Graphic_handler grap = new Graphic_handler(bot);
                      ^^^^ this *hides* the other grap
      grap.start();
   }
    
}

To fix this just remove the declaration in front of grap in the method.

class SomeClass {

   Graphic_handler grap;

   public static void main(String[] args) {
      grap = new Graphic_handler(bot);
      grap.start();
   }
    
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement