鼠标在JScrollPane中相对于ImageIcon的坐标

时间:2014-08-12 02:31:46

标签: 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.");
        }
    });

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

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

1 个答案:

答案 0 :(得分:4)

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

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

enter image description here

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了解详情