JScrollPane 中相对于 ImageIcon 的鼠标坐标

Ish*_*awa 3 java swing jscrollpane mouselistener imageicon

我正在用 Java 构建一个桌面应用程序。我想获取相对于 JSrollPane 中的图像的鼠标单击的鼠标坐标。JScrollPane screenScroll 包含在带有 BorderLayout 的 JPanel 中。

    final JLabel screenLabel = new JLabel(new ImageIcon(image));
    JScrollPane screenScroll = new JScrollPane(screenLabel);
    screenScroll.getViewport().setBackground(Color.white);

    screenLabel.addMouseListener(new MouseAdapter() {

        @Override //I override only one method for presentation
        public void mousePressed(MouseEvent e) {
            System.out.println("Y'all clicked at: "+e.getX() + ", " + e.getY()+" in the image.");
        }
    });
Run Code Online (Sandbox Code Playgroud)

所以这里的问题是:JPanel 比图像大,JScrollPane 占据了 JPanel 的 100%(看起来不错,我很高兴)但是 mousePressed 事件给了我相对于 JScrollPane/JPanel 的坐标,而不是图像,所以 x 坐标是偏移的(即使 mouseListener 被添加到包含 ImageIcon 的 JLabel)。

希望我解释清楚。如何修改上面的代码以获取相对于图像的坐标?

Mad*_*mer 6

基本上,使用 a 来实现这一点是非常困难的,JLabel因为图像的实际位置是由JLabel的外观和感觉委托决定的。虽然您可以创建自己的委托,但您最终需要为每个受支持的平台创建一个委托,而且……我太懒了……

相反,您可以创建一个自定义组件并按照您想要的方式渲染图像。然后,您将能够更好地确定图像的位置并转换您需要的鼠标点值,例如...

在此处输入图片说明

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }

                    BufferedImage img = ImageIO.read(new File("C:\\hold\\thumbnails\\MT015.jpg"));
                    final ImagePanel imgPane = new ImagePanel(img);
                    JScrollPane scrollPane = new JScrollPane(imgPane);
                    final JLabel report = new JLabel("...");

                    imgPane.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            Point panelPoint = e.getPoint();
                            Point imgContext = imgPane.toImageContext(panelPoint);

                            report.setText("You clicked at " + panelPoint + " which is relative to the image " + imgContext);
                        }
                    });

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(scrollPane);
                    frame.add(report, BorderLayout.SOUTH);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public class ImagePanel extends JPanel {

        private BufferedImage img;

        public ImagePanel(BufferedImage img) {
            this.img = img;
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(), img.getHeight());
        }

        protected Point getImageLocation() {

            Point p = null;
            if (img != null) {
                int x = (getWidth() - img.getWidth()) / 2;
                int y = (getHeight() - img.getHeight()) / 2;
                p = new Point(x, y);
            }
            return p;

        }

        public Point toImageContext(Point p) {
            Point imgLocation = getImageLocation();
            Point relative = new Point(p);
            relative.x -= imgLocation.x;
            relative.y -= imgLocation.y;
            return relative;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                Point p = getImageLocation();
                g.drawImage(img, p.x, p.y, this);
            }
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看执行自定义绘画2D 图形