(java) mouselistener in JPanel
Hi
I have a JPanel which is full of JLabels. The JPanel has a mouseListener and I am using the mouse event object to determine the location of where i have clicked. If i click on a JLabel in the JPanel can i have returned the name of the JLabel ?? At present i am returned the source as the panel name and the coordinates of the click. I know i could implement a listener on every JLabel but if i dont have to do this i can save a lot of code. help much appreciated |
I don't believe so (from a quick glance). If you use MouseEvent's getSource() you'll always get the panel. The alternative to having a listener for each JLabel is to create one listener and then pass it to all the labels. Within this one listener you could figure out which label was actually pressed using the said getSource() method (and then possibly use a case switch to figure out what to do depending on what label was pressed).
Example: Code:
MouseListener listener = new MouseAdapter() { |
It can be done if that's really the way you want to do it eg. one way like this
Code:
|
Awesome, you learn something new everyday.
|
excellent, thanks very much to you both !!
but i have a few questions if you have the time . . you (lookingLost) seem to suggest that this isn't an ideal solution, why might it better to do things another way ? . . but maybe you just felt like calling the class labelMadness ! also could you please explain what is happening here, ive never seen a construction like this. Code:
this.addMouseListener(new MouseAdapter() |
It's an annonymous class, a way for you to quickly extend a class without ever naming it. It's more or less a shortcut, but you can do it the old fashion way as well:
Code:
class MyMouseListener extends MouseAdaptor { Hope this helps. |
yes thats a good explanation
thanks :) |
All times are GMT -5. The time now is 05:25 AM. |