I'am trying to make a little game for academic stuff. What I want to do is to make a random number of balls move inside a JPanel
, with random directions, but when I click inside of the ball it should sysout the actual coords of the ball. Here is my class without the move methods (I already made it but don't need to post it for this question):
public class Ball implements Runnable {
int x = UserInterface.BALL_START;
int y = 0;
int size = 10;
Color color;
public Ball() {
Random random = new Random();
int r, g, b;
r = random.nextInt(256);
g = random.nextInt(256);
b = random.nextInt(256);
color = new Color(r,g,b);
y = random.nextInt(500);
}
public void run() {
int vx = (new Random()).nextInt(10) + 1;
while (x < UserInterface.BALL_END) {
x += vx;
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
x = UserInterface.BALL_END;
}
public int getX() {
return x;
}
public void paint(Graphics g) {
g.setColor(color);
g.fillOval(x - size / 2, y - size / 2, size, size);
}
}
How can I add a mouselistener to the ball class without make it as a JComponent
or JLabel
or JPanel
?