I have a Ball class which I want to have extend JComponent and implement mouseListener.
public class Ball extends JComponent implements MouseListener {
Int x, y, radius;
public Ball(int X, int Y, int Radius){
//contains only three ints and redefines x,y,radius
x=X;
y=Y;
radius=Radius;
}
public void draw(Graphics g){
//draw oval using x,y,radius
}
//5 mouselisteners undefined yet
}
So ball is the constructor which is used by a panel which is within a frame.
Sorry I have not yet entered all the code. I will submit my complete code soon.
So what I would have to do is use MouseEntered listener in the ball class so that when the mouse enters the component (the ball/oval) . But I don't know how to define the component so that it knows it has been entered. Does it need some dimensions? Because all I am doing is using the draw function in a panel.
If this were my class, I wouldn't have it extend JComponent and wouldn't give it a MouseListener or MouseMotionListener especially if I wanted to display multiple balls in a single JComponent. Instead I would give it public methods that allow other classes to get its boundaries (such as is available from the Shape interface), and whether something is contained in the shape or not (again the Shape interface works well for this), and other public methods that allow outside classes to change the state (appearance?) of this object.
I would then have a JComponent hold one Ball or an ArrayList<Ball>
, and in the MouseListener/MouseMotionListener/MouseAdapter for this JComponent, iterate through the ArrayList<Ball>
seeing if the mouse is inside of any ball, and if so, change that ball's state. Then in the JComponent's paintComponent method, I'd iterate through the ArrayList<Ball>
calling draw(g)
on each Ball contained.