Chris Lovering
Chris Lovering

Reputation: 3

mouse listener for array of JPanels

I have got an array of JPanels which themselves contain ImageIcons, I have added this array JPanels to a single JPanel (as I'm using a Scroll Pane). While adding these JPanels I added a mouse listener to each of them, my question is, is it possible to write a single Event handler that can use e.getSource() or other such method where I can extract the JPanel and such the ImageIcon from which one was clicked.

This may sound complicated as I cannot explain my situation very well, but below are some relevant snippets of code I have so far.

imageArray=new BufferedImage[256];
imageLabelArray = new JLabel[256];

...

imageArray[i] = volume.getSlice(image, face, i);//this returns an image
scaledImage = imageArray[i].getScaledInstance(25,25,
                    Image.SCALE_SMOOTH);
imageLabelArray[i] = new JLabel(new ImageIcon(scaledImage));
imageLabelArray[i].addMouseListener(this);

...

for(int i=0;i<255;i++){
    panel.add(imageLabelArray[i]);
}

...

public void mouseClicked(MouseEvent e) {
    // TODO extract image data
    dispose();
}

I can answer any questions that could clear up the problem itself and i will be editing the question to match.

Upvotes: 0

Views: 139

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347332

Write a class which extends from JPanel which has a getter (and probably a setter) which allows you to manage the image. The rest of the answer then becomes yes.

Simply cast the MouseEvent#getComponent result to your "panel" type and you then have access to the functionality to get/set the image

Upvotes: 1

Related Questions