views:

82

answers:

2

Suppose I have 4 squares colored blue, white, red and green (myComponent) associated with the mouse press event. At one point, the mouse is pressed over one of them - say, the yellow one - and the event is activated.

Now, the control flux is inside the event handling function. How do I get the MyComponent - the yellow square - that caused this from here?

EDIT

I have another question. Is there a way to tell the position of the component? My problem is a bit more complicated than what I said.

Basically, I have a grid full of squares. When I click one of the squares, I have to know which one it is, so I can update my matrix. The thing is, if I calculate it myself, it only works on a given resolution.

I have a GridBagLayout, and inside it are the myComponents. I have to know which one of the components exactly - like, component[2][2] - caused the interruption.

I mean, I can tell which one of the components did it, but not where in the matrix it is located.

+4  A: 

MouseEvent.getSource() returns the object on which the event initially occurred.

I have a GridBagLayout, and inside it are the myComponents. I have to know which one of the components exactly - like, component[2][2] - caused the interruption.

You could store the indices, e.g. (2,2), inside each myComponent when you add them to the matrix. That way, given the component, you can always identify its position in the matrix.

class MyComponent extends JButton
{
    final int i; // matrix row
    final int j; // matrix col

    // constructor
    MyComponent(String text, int i, int j)
    {
        super(text);
        this.i = i;
        this.j = j;
    }

    ...
}
Zach Scrivena
+1  A: 

By adding a MouseListener (or alternatively, a MouseAdapter, if you don't need to override all the MouseListener' methods) to each of your colored boxes, when an event such as a mouse click occurs, the MouseListener will be called with a [MouseEvent`][3], which can be used to obtain the component that was clicked.

For example:

final MyBoxComponent blueBox =   // ... Initialize blue box
final MyBoxComponent whiteBox =  // ... Initialize white box
final MyBoxComponent redBox =    // ... Initialize red box
final MyBoxComponent greenBox =  // ... Initialize green box

MouseListener myListener = new MouseAdapter() {
    public void mouseClicked(MouseEvent e)
    {
        // Obtain the Object which caused the event.
        Object source = e.getSource();

        if (source == blueBox)
        {
            System.out.println("Blue box clicked");
        }
        else if (source == whiteBox)
        {
            System.out.println("White box clicked");
        }
        // ... and so on.
    }
};

blueBox.addMouseListener(myListener);
whiteBox.addMouseListener(myListener);
redBox.addMouseListener(myListener);
greenBox.addMouseListener(myListener);
coobird