-
December 28th, 2010, 04:42 PM
#1
Animation not stopping
Someone told me that one (or more) redraw(s) is/are triggered even after I do timer.stop(). I just cannot see how and would really appreciate it if someone could bring it out in an obvious way.
Anyways, here is the code:
Code:
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Bounds extends JPanel
{
int x = 50, y = 50, width = 20, height = 20;
Timer timer;
public Bounds()
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
ActionListener listener = new graphicsListener();
timer = new Timer(200, listener);
timer.start();
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g); // so that the background gets refreshed
g.drawRect(x, y, width, height);
System.out.println("Panel width: " + getWidth() + " Panel height: " + getHeight());
System.out.println("x+width = " + (x+width));
System.out.println("y+height = " + (y+height));
if(x+width >= getWidth() || y+height >= getHeight())
{
System.out.println("Out of bounds!");
JOptionPane.showMessageDialog(null, "Out of bounds!");
timer.stop(); // Why isn't this having an effect?
}
x+=10;
y+=10;
width+=20;
height+=20;
}
public class graphicsListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
repaint();
}
}
public static void main(String[] args)
{
new Bounds();
}
}
Any help would be greatly appreciated!
Thanks in advance!
-
December 28th, 2010, 05:35 PM
#2
Re: Animation not stopping
javax.swing.Timer uses it's own thread to to perform the waiting for and triggering of events but the action event handlers execute on another thread the event-dispatching thread. This makes it easy to interact with the GUI as all GUI operations have to be done on the event-dispatching thread but it does mean there is a disconnection between the events been triggered and being handled.
Therefore, if your timer triggers events quicker than the event-dispatching thread can process them they will be queued in the event-dispatch queue. When you stop the timer from running no more events will be added to the event-dispatch queue but any events still in the queue will be processed.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|