Strange text output of e.getSource() on MouseEvent e

286 views Asked by At

I want to be able to print MouseEvent e, I have seen people using the getSource() method to do this, however mine doesn't give the exact output I want. In other code people print e.getSource() and it gives the direct path to the image.

When I print e.getSource():

javax.swing.JLabel[,224,7,23x20,alignmentX=0.0,alignmentY=0.0,border=,flags=8388608,maximumSize=,minimumSize=,preferredSize=,defaultIcon=file:/C:/Users/Sam/workspace/RS%20Calculator/bin/Hitpoints_icon.png,disabledIcon=,horizontalAlignment=C ENTER,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=,verticalAlignment=CENTER,verticalTextPosition=CENTER] 

This output includes the image path that I want to access - but also lots of other random information.

How can I get to print only the image path? (/C:/Users/Sam/workspace/RS%20Calculator/bin/Hitpoints_icon.png)

    for(JLabel j : jLabelArray){
        j = new JLabel(imageIcons[n]);

        j.addMouseListener(new MouseAdapter(){

            @Override
            public void mouseClicked(MouseEvent e){
                setSize(650,400);
                System.out.println(e.getSource());
                iconClicked(e);
            }

        });

        add(j);
        n++;
    }
1

There are 1 answers

1
Hovercraft Full Of Eels On

The source returned by Java is correct since the MouseListener was added to the JLabel and not to an image. If you want the ImageIcon that the label contains, then simply extract it. Note that you're usually better off using the mousePressed method rather than mouseClicked.

@Override
public void mousePressed(MouseEvent e) {
   JLabel label = (JLabel) e.getSource();
   ImageIcon icon = label.getIcon();
   // ....
}

As a side rec, this troubles me:

setSize(650,400);

You should usually avoid trying to set sizes of things. Mind if I ask, what are you trying to achieve with this?