Multiple Swing Timers in Java

Status
Not open for further replies.
I have a Ball object which has a swing timer which invokes a checkNewPosition() method, the JPanel that creates the Balls also has a timer to invoke render calls to draw the balls. The problem is the more 'Balls' I create the slower the timers fire. The timer is set to every 10 millis (which is the lowest value) 1 timer is fine, 4 or 5 are way off point. The timer used to draw the balls in the JPanel class fires fine, just the timer in the balls, perhaps I need a single timer for all the balls. Weird thing is CPU usage is <1%. Are they conflicting with eacth other?

Any solution?

Thabks
 
Every 10 milliseconds, eh? 1000ms / 10ms = 100 frames per second. Do
you really need to draw that often? I don't entirely understand your
problem, but perhaps you need to employ some basic AWT tricks such as
overriding update() (which clears the component and then calls paint)
to just call paint like so.

code:<HR>
Code:
public void update(Graphics g) {
    paint(g);
}

And maybe you need to look into double-buffering, too. Basically you
make a new Image the size of the component, call getGraphics() on it
and draw on that graphic object. Then all your paint method has to do
is blit up the image like so...

code:<HR>
Code:
private Image monkey;
private Graphics drawOnMe;<P>Constructor() {
    monkey = new Image(getWidth(), getHeight());
    drawOnMe = monkey.getGraphics();
}<P>public void ballDraw() {
    drawOnMe.drawOval(...);
}<P>public void paint(Graphics g) {
    g.drawImage(monkey, 0, 0);
}

Hope this helps. There are plenty of tutorial like things out there
for free on double buffering, just hit teh Google.

~Kevin
:)
 
Ah, I see your problem. A quick look at the API shows that
javax.swing.Timer doesn't extend java.lang.Thread, so it must be using
another thread to do the events. A quick look at the How to Use Timers tutorial (which is linked in the first paragraph
of the API docs) says "Note that the Swing timer's task is performed in
the event-dispatching thread."


Read the documentation more carefully and you should be okay.

~Kevin
:)
 
Status
Not open for further replies.