Reputation: 185
I am new to Java and right now i am trying to understand Threads.
I am currently working on a "make the ball bounce or you lose" game.
In this game there is a ball that bounces of a "wall" or a "Girder".
The Wall moves with the x position of the cursor. no y movement.
Now i can't use Timer because if i do that i will have the same delay for MouseMotion and Ball Movement.
What i am trying to achieve is getting the mousemotion information with a delay of 10ms and the ball movement with a delay of 200 ms.
With Timer i have to choose either delay for both wall and ball. 10ms is great for the wall movement as it moves instantly when i move my mouse but it is way too fast for the ball movement. not even chuck norris could move the mouse so fast to let the ball bounce off the wall.
I tried creating 2 different Timers but it won't accept the mouse listener. ActionListener
s are the only Listeners the Timer
accepts but for some reason it still triggers the mouse motion method beside the actionPerformed
method if I use a single timer with this
as the parameter. But that gives me the same delay for both ball and wall.
So that is why I need threads to do it. But I have no idea how to get the mouse motion information from the MouseListener
to paintComponent
within a Thread
.
I hope you guys understand my problem.
EDIT:
This is how i am now trying to get a wall delay of 10ms and ball delay of 200ms:
private Timer trigger = new Timer(200, this);
private Timer wall = new Timer(10, this);
in paintComponent
if ((start.getText() == "Spiel aktiv..." || trigger.isRunning() == true) || wall.isRunning() == true) {
g.setColor(new Color(255, 254, 102));
g.fillRect(x, screen.getHeight() - 15, length, 10);
}
if ((start.getText() == "Spiel aktiv..." || trigger.isRunning() == true) && wall.isRunning() == false) {
ball_x = ball_x + dx;
ball_y = ball_y + dy;
if (ball_x > (screen.getWidth() - 100) || ball_x < 10) {
dx = -dx;
bounce = true;
}
if (ball_y > (screen.getHeight() - 115) || ball_y < 10) {
dy = -dy;
bounce = true;
}
}
g.setColor(new Color(103, 104, 255));
g.drawRect(ball_x, ball_y, 100, 100);
g.setColor(new Color(255, 254, 102));
g.fillOval(ball_x, ball_y, 60, 60);
}
}
in actionPerformed i start the wall and trigger(ball) timers as soon as start is clicked by the user.
But i can't get the ball and wall timers to work seperately. wall timer is faster and does a complete repaint but i just want it to repaint the wall not the ball.
Upvotes: 0
Views: 280
Reputation: 57381
Add your listener (the Maus extends MouseMotionAdapter
) as usual without any additional threads. Event Dispather Thread is used to process mouse events.
Use javax.swing.Timer
with any desired delay just to change the ball position.
Upvotes: 1