JScrollPane中相对于ImageIcon的鼠标坐标

问题描述 投票:2回答:1

我正在用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.");
        }
    });

所以这是问题:JPanel大于图像,并且JScrollPane占据了JPanel的100%(看起来不错,对此我感到高兴),但是mousePressed事件为我提供了相对于JScrollPane的坐标/ JPanel,而不是图像,因此x坐标是偏移的(即使mouseListener已添加到包含ImageIcon的JLabel中)。

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

java swing jscrollpane mouselistener imageicon
1个回答
5
投票

[基本上,使用JLabel很难做到这一点,因为图像的实际位置由JLabel的外观代表确定。虽然您可以创建自己的委托,但最终需要为每个受支持的平台创建一个委托,并且...我太懒了...

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

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9EcmZtNC5naWYifQ==” alt =“在此处输入图像说明”>

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);
            }
        }

    }

}

[查看Performing Custom Painting2D Graphics了解更多详细信息

© www.soinside.com 2019 - 2024. All rights reserved.