First off, I came to Java as a website programmer. In JavaScript, all you have to do to add a mousemove, mouseover, or click event is call an addEventListener function. From my limited experience with Java, you can't just implement the MouseListener interface from any object.
Basically, what I have so far is a JPanel, that paints some shapes (a CustomShape object with a paint method) that have x/y/width/height values. I want to add some type of mouse listener to the shape object, so that I can fire move/roll/click events for the shape. Just implementing the MouseListener interface to the CustomShape object doesn't work (for what I suppose are obvious reasons). I've looked up how to design custom event listeners, but it doesn't seem as though making a custom mouse listener is possible.
I eventually resorted to adding the mouse listener to the JPanel, and then looping through all the shape objects. If the shape object had a 'listener' attached, and the mouse coordinates verified the mouse event had occurred, it fired the method. Initially, it was fine, but as the application got more developed, it started getting really really messy. Plus, I would never be able to copy over the shape objects/interfaces to another application without copying a bunch of code.
As a simple illustration: (the actual code is quite large)
Interface CustomShape{
int width, height, x, y;
void paint(Graphics g);
}
public class StarShape implements CustomShape{
int width, height, x, y;
public StarShape(){
width = 100;
height = 100;
x = 50;
y = 50;
}
void paint(Graphics g){
g.setColor(Color.black);
g.draw(new Rectangle(x,y,width,height));
}
}
public class Main extends JPanel{
StarShape check = new StarShape();
public Main(){ }
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
check.paint(g);
}
}
So, I was wondering if there is a clean way of implementing some type of mouse listener for a 'hand-drawn' shape.