Results 1 to 16 of 16
  1. #1
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Question Stop a timer in other class

    Heey all!

    I'm trying to stop a timer with a button, and the timer is in a other class. How to fix it? (Timer is public)

    Verblijf.java:
    Java Code:
    	public Verblijf()
    	{
    		booleanGenerator = new Random();
    		random = new Random();
    		
    	    addMouseListener(this);
    		willekeurigDier();
    
    	    timer = new Timer(150, this);
    	    timer.start();
    	    timer2 = new Timer(2000, this);
    	    timer2.start();
    	}
    Now I want to stop the timer from the class 'Knoppenbalk.java'. I've tried:

    Java Code:
    	public Verblijf verblijf = new Verblijf();
    (...)
    		knop1 = new JButton("Knop1 ");
    		knop1.addActionListener(this);
    		add(knop1);
    (...)
    	public void actionPerformed(ActionEvent e)
    	{
    		verblijf.timer.stop();
    	}
    Thanks in advance!

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

    Default

    One way: Give the class that holds the Timer a public method, say timerStop(), and in this method, stop the Timer if it's not null. Then call this method from the other class. You'll of course need a reference to the object that holds the Timer.

  3. #3
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Default

    Hmm.. I tried, but didn't work. I guess the problem is in the refference:

    Java Code:
    	Verblijf verblijf = new Verblijf();
    I do not want to make a new 'Verblijf', because the 'Verblijf' does already exists... but without the '= new Verblijf();' it give a nullpointer exeption...

    By the way, I made this method, I guess that's okay:

    Java Code:
    	public void timerStop()
    	{
    		if(timer != null && timer1 != null)
    		{
    			System.out.println("testje");
    			timer.stop();
    			timer2.stop();
    		}
    	}
    The system.out.println does work and showed up when I press the buttons. The timer just keeps going...!

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

    Default

    Quote Originally Posted by warchieflll View Post
    Hmm.. I tried, but didn't work. I guess the problem is in the refference:

    Java Code:
    	Verblijf verblijf = new Verblijf();
    I do not want to make a new 'Verblijf', because the 'Verblijf' does already exists... but without the '= new Verblijf();' it give a nullpointer exeption...
    If you create a new object, you'll stop a timer that is not being used -- makes no sense. So just use the object that already exists then. You can pass a reference to it into the current class via a method or constructor parameter.

    By the way, I made this method, I guess that's okay:

    Java Code:
    	public void timerStop()
    	{
    		if(timer != null && timer1 != null)
    		{
    			System.out.println("testje");
    			timer.stop();
    			timer2.stop();
    		}
    	}
    The system.out.println does work and showed up when I press the buttons. The timer just keeps going...!
    Again of course the timer keeps going because none of this code effects the timers that are actually running. As for you method above, it's fine as long as you're absolutely sure that either both timers are non-null or null. If not, then you may wish to use two if blocks, one for each timer.

  5. #5
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Default

    Sounds logical. I just don't get how to set the refference: 'You can pass a reference to it into the current class via a method or constructor parameter.'

  6. #6
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Default

    Any idea how to fix it?

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

    Default

    Quote Originally Posted by warchieflll View Post
    Any idea how to fix it?
    Not a code fix, no, as you have the code. But I can give general suggestions. If you have one class that needs to call methods of another class (object), you can give the first class a field to hold a reference to the second class, and pass a reference of the second class into the first class via a parameter. For instance say you have this class:

    Java Code:
    public class ClassWithTimer {
      private Timer timer;
      //... holds a lot more code of course
    
      public void stopTimer() {
         //... methods to stop Timer object
      }
    }

    And then you have another class that needs to stop the Timer, OtherClassThatNeedsToStopTimer, then give it fields and methods like so:

    Java Code:
    public class OtherClassThatNeedsToStopTimer
      private ClassWithTimer classWithTimer;
    
      public void setClassWithTimer(ClassWithTimer classWithTimer) {
          this.classWithTimer = classWithTimer;
      }
    
    }

    So if you pass in a valid reference to the current instance of the first class (perhaps wherever you initiate these classes), then the second class can call

    Java Code:
      classWithTimer.stopTimer();
    somewhere in its code.

  8. #8
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Default

    Hmm... I understand what is happening, but I coudn't fix it in my code. Right now when clicked on the button, it looks like the 'classWithTimer' (so in my example 'dier') is null.

    My class timer has a public void stopTimer();. The class who needs to stop the timer looks like the following:

    Java Code:
    	private Dier dier;
    (...)
    	public void Dier(Dier dier)
    	{
    		this.dier = dier;
    		dier.stopTimer();
    	}
    
    	// niet in gebruik bij stap0.
    	public void actionPerformed(ActionEvent e)
    	{
    		Dier(dier);
    	}
    Last edited by warchieflll; 02-02-2011 at 12:12 PM.

  9. #9
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Default

    I see the problem I guess. You explanation was very good, and I get it to work in another part of the code. The problem is the following:

    I have a button bar (knoppenbalk), and this is made in the frame-class. I coudn't say in the frameclass:

    Java Code:
    Knoppenbalk knoppenbalk = new Knoppenbalk();
    knoppenbalk.geefDier(dier);
    because the 'dier' doesn't exist yet.

    I also could not set it in the class where the animal (dier) is made, because the knoppenbalk isn't made in that class:

    Java Code:
    private Knoppenbalk knoppenbalk;
    (...)
    	public void mouseClicked(MouseEvent e)
    	{	
    		(...)
    		huidigDier = new Dier(dierSoort, 50, randomBoolean);
    		(...)
    		knoppenbalk.geefDier(huidigDier);
    	}
    Maybe this post is more clearly.
    Last edited by warchieflll; 02-02-2011 at 02:16 PM.

  10. #10
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Default

    Sry for all the posts. I found this intresting:

    Java Code:
    	public void geefDier(Dier dier)
    	{
    		 System.out.println(this.dier);
    		 this.dier = dier;
    		 System.out.println(this.dier);
    	}
    
    	// niet in gebruik bij stap0.
    	public void actionPerformed(ActionEvent e)
    	{
    		System.out.println(this.dier);
    		dier.stopTimer();
    	}
    this results in:

    null
    SaveLoadStopStart.Dier[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignm entX=0.0,alignmentY=0.0,border=,flags=9,maximumSiz e=,minimumSize=,preferredSize=]
    null
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at SaveLoadStopStart.Knoppenbalk.actionPerformed(Knop penbalk.java:52)

    So... it doesn't keep 'dier' when pressed the button? How to slove this problem?

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

    Default

    I'm sorry, but I'm not sure how to help you based on the code you've posted. Consider creating a small compilable and runnable program that demonstrates your problem an SSCCE, and then posting it here.

  12. #12
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Default

    I tried to make a simple program, but coudn't really get to the problem because of all those classes. I deleted some code, and I'll post the shorter version.

    In my opinion for my problem is the startup class interesting, the animal class, and the buttonbar class. I deleted some code to make it shorter:

    StartUp class // class to startup the program:

    Java Code:
    package SmallProgramTest;
    
    IMPORTS
    
    public class StartUp extends JFrame
    {
    	public StartUp()
    	{
    		JFrame venster = new JFrame();
    
     		venster.SETTINGS...
    
    		Panel paneel = new Panel();
    		ButtonBar knoppenbalk = new ButtonBar();
    
    		venster.add(paneel);
    		venster.add(knoppenbalk, BorderLayout.NORTH);
    		venster.setVisible(true);
    	}
    
    	public static void main(String[] args)
    	{
    		new StartUp();
    	}
    }
    From the startup you go to the created panel:

    Java Code:
    package SmallProgramTest;
    
    IMPORTS
    
    public class Panel extends JPanel implements MouseListener, MouseMotionListener
    {
    	private int startX, startY;
    	public boolean dragged = false; // nodig om op deze manier maar 1 kooi te maken, en niet vele kooien zolang er 'gedragd' wordt
    	private Class1 class1;
    	
    	public Panel()
    	{
    	    addMouseListener(this);
    	    addMouseMotionListener(this);
    	}	
    	public void mousePressed(MouseEvent e)
    	{
    	    startX = e.getX();
    	    startY = e.getY();
    	}
    
    	public void mouseDragged(MouseEvent e)
    	{    
    		if (!dragged)
    		{
    			Class1 class1 = new Class1();
    			add(class1);
    			class1 = class1;
    			dragged = true;
    		}
    		class1.setCage(startX, startY, e.getX(), e.getY());
    	}
    		
    	public void mouseReleased(MouseEvent e)
    	{
    		dragged = false;
    	}
    
    	MouseListeners NOT IN USE
    }
    From here you see a class1 will be created:

    Java Code:
    package SmallProgramTest;
    
    IMPORTS
    
    public class Class1 extends Class2
    {
    	private Random generator;
    	
    	public Class1()
    	{
    	    willekeurigDier();
    	}
    	  
    	public void willekeurigDier()
    	{
    		generator = new Random();
    		RandomDier = generator.nextInt( 3 ) + 1;
    	    switch ( RandomDier )
    	    {
    	        case 1 : dierSoort = "aap";
    	            break;
    	        case 2 : dierSoort = "beer";
    	            break;
    	        case 3 : dierSoort = "cheetah";
    	            break;
    	     }
    	}
    
    	public void setCage(int x, int y, int x2, int y2)
    	{
    		... CALCULATION POSITION...
    	}
    	
    	public void paintComponent(Graphics g)
    	{
    		... PAINTING A CAGE ...
    	}
    }
    Here you see class1 is a class 2:

    Java Code:
    package SmallProgramTest;
    
    IMPORTS
    
    public class Class2 extends JPanel implements MouseListener
    {
    	protected Point positie;
    	protected int breedte, hoogte;
    	protected String dierSoort;
    	protected int RandomDier, dx, dy;
    	private ArrayList<Animal> dierenLijst = new ArrayList<Animal>();
    	public Animal huidigDier;
    	protected boolean randomBoolean;
    	private Random booleanGenerator;
    
    	public Class2()
    	{
    		booleanGenerator = new Random();
    		
    	    addMouseListener(this);
    		willekeurigDier();
    	}
    	
    	public int getXPos()
    	{
    		return getX();
    	}
    	  
    	public void willekeurigDier()
    	{
    		dierSoort = "dier";
    	}
    		
    	public void mouseClicked(MouseEvent e)
    	{	
    		randomBoolean = booleanGenerator.nextBoolean();
    		
    		huidigDier = new Animal(dierSoort, 50, randomBoolean);
    	 	dierenLijst.add(huidigDier);
    		add(huidigDier);
    		huidigDier.setBounds(e.getX(), e.getY(), 50, 50);
    		huidigDier.geefVerblijf(this);
    	}
    
    	... MOUSE EVENTS NOT IN USE ...
    }
    A new animal will be created. So here the animal class:

    Java Code:
    package SmallProgramTest;
    
    IMPORTS
    
    public class Animal extends JPanel implements MouseListener, ActionListener
    {
    	private int size, dx, dy;
    	private String soort;
    	private ImageIcon dierIcoon;
        JLabel imgLabel;
    	private Timer timer, timer2;
    	private Random random;
    	private Class2 verblijf;
    	
    	public Animal (String soort, int size, boolean vrouwtje)
    	{
    		setOpaque(false);
    	    addMouseListener(this);
    		random = new Random();	
    	    
    		this.soort = soort;
    		this.size = size;
    		
    		maakIcoon();
    		
    	    timer = new Timer(150, this);
    	    timer.start();
    	    timer2 = new Timer(2000, this);
    	    timer2.start();
    	}
    	
    	public void stopTimer()
    	{
    		timer.stop();
    		timer2.stop();
    	}
    	  
    	public void maakIcoon()
    	{
    		dierIcoon = new ImageIcon(Animal.class.getResource("/pics/" + soort + ".png"));
    		imgLabel = new JLabel(dierIcoon);
    		imgLabel.setBounds(0, 0, size, size);
    		add(imgLabel);
    	}
    		
    	
    	public void geefVerblijf(Class2 verblijf)
    	{
    		 this.verblijf = verblijf;
    	}
    	
    	public void actionPerformed(ActionEvent e)
    	{
    		if(e.getSource() == timer)
    		{
    			...TIMER CODE...
    		}
    		if(e.getSource() == timer2)
    		{
    		      ... TIMER 2 CODE...
    		}
    	}
    
    	... MOUSE EVENTS NOT IN USE:
    }
    The class that is left is the buttonbar:

    Java Code:
    package SmallProgramTest;
    
    IMPORTS
    
    public class ButtonBar extends JPanel implements ActionListener
    {
    	private JButton knop1, knop2, knop3, knop4, knop5;
    	private JTextField tekstvak1, tekstvak2;
    	
    	public ButtonBar()
    	{
    		knop1 = new JButton("Knop1 ");
    		knop1.addActionListener(this);
    		add(knop1);
    		
    		... 4 MORE BUTTONS, 2 TEKST FIELDS...
    	}
    
    	public void actionPerformed(ActionEvent e)
    	{	
    		// when pressing button 1, the timer in the class 'Animal' needs to stop...
    	}	
    }
    Last edited by warchieflll; 02-02-2011 at 07:51 PM.

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

  14. #14
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Default

    Didn't work 100% because I deleted come of the code to make it shorter... however it's still long. Grr... I just don't get it! Anyway, thanks for your efforts!

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

    Default

    It looks like you have your Animal objects inside of the Class2 which is extended by Class1, which is held inside of Panel class. So you've got refences buried far away from each other, and it will take some work getting them to communicate, but it can be done. You may want to consider first of all refactoring your code so that the classes can more easily communicate. Either that or you could have methods that percolate down a bunch of classes til they reach their destination... ugh.

  16. #16
    warchieflll is offline Member
    Join Date
    Dec 2010
    Posts
    55
    Rep Power
    0

    Default

    Hmm yea I see... that's why it was so difficult to program! Anyway, I've some work to do I guess... thanks very much for your help!!

Similar Threads

  1. Use stop button to stop moving (stop timers) on JPanel
    By mneskovic in forum New To Java
    Replies: 3
    Last Post: 07-23-2010, 12:50 PM
  2. How to make swing.Timer as a separate class
    By nethz13 in forum New To Java
    Replies: 9
    Last Post: 04-18-2010, 09:14 AM
  3. Help with Timer Class
    By morfasto in forum New To Java
    Replies: 2
    Last Post: 11-03-2009, 09:13 PM
  4. Replies: 0
    Last Post: 06-26-2008, 07:32 PM
  5. Replies: 0
    Last Post: 02-05-2008, 10:59 AM

Tags for this Thread

Posting Permissions

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