Search code examples
javaswingjlabelimageiconnull-layout-manager

Getting the X and Y position of the mouse when it is clicked on the image in JLabel


I have a Image displayed inside JLabel using ImageIcon feature.

The JLabel is contained inside a JPanel.

When image is clicked, I want to get the mouse position relative to the image.

I am trying to solve this problem by adding mouse listener to the JLabel which contains the image.

Apparently, even if I set the size of JLabel with the width and height of the image, it seems that JLabel automatically stretches out to the size of JPanel.

So when below code runs, if the size of image is smaller than the JPanel, getting X and Y position returns the unwanted value.

Is there a way that I can specifically limit the size of the JLabel so that getting X position and Y position of the mouse will work fine?

Or better way to get a mouse position relative to the image? (which would be better)

    ImageIcon icon = new ImageIcon(image);

    JLabel imageLabel = new JLabel(icon);
    imageLabel.setSize(image.getWidth(null), image.getHeight(null));

    imageLabel.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {
            JOptionPane.showMessageDialog(imageLabel, e.getX()+" "+e.getY());
        }
    });

    imageLabel.validate();
    panel.add(imageLabel);
    panel.validate();

Solution

  • It is all about the layout.

    See this example for the above image.


    It would seem this use-case requires a GridBagLayout or BoxLayout.