显示图像和捕获鼠标单击不会同时起作用

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

我想做的事:

我想写一个可以显示图像的小应用程序。用户必须能够放大和缩小图像,移动图像并在图像上标记点。我想进一步了解点击的点数,但我还没有。

到目前为止我所拥有的:

为了追查我的问题,我写了一个MVCE:

用于处理JFrame的GUI类(以及稍后的其他UI元素):

import javax.swing.*;
import java.net.MalformedURLException;
import java.net.URL;

public class MCVE_GUI {

    public static void main(String[] args) throws MalformedURLException {
        MCVE_ZoomPane zp = new MCVE_ZoomPane(new URL("https://fiji.sc/site/logo.png"));

        JFrame f = new JFrame("PictureMeasurement");
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        f.setContentPane(zp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.revalidate();
        f.repaint();
        f.setVisible(true);
    }
}

ZoomPanel用于处理图像和缩放:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;

class MCVE_ZoomPane extends JPanel implements MouseMotionListener {

    MCVE_ZoomPane(URL url){
        JLabel image = new JLabel();
        JScrollPane jsp = new JScrollPane(image);

        //image.setIcon(new ImageIcon(url)); // picture, no input
        //jsp.setPreferredSize(new Dimension(300,300)); //picture, no input
        jsp.setPreferredSize(image.getPreferredSize()); //depends on position of image.setIcon
        image.setIcon(new ImageIcon(url));  //no picture, input

        this.add(jsp);
        this.setPreferredSize(image.getPreferredSize());
        this.addMouseMotionListener(this);
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
    }

    public void mouseDragged(MouseEvent e) {
        System.out.format("Dragged X:%d Y:%d\n",e.getX(), e.getY());
    }

    public void mouseMoved(MouseEvent e) {}
}

问题:

根据我放置image.setIcon(new ImageIcon(url))的位置,我可以显示图像,也可以听鼠标点击,但不能同时听两次。如果我将JScrollPane设置为固定的首选大小而不调用image.getPreferredSize()我总是得到一张图片但没有输入。

java image swing interactive
1个回答
0
投票

显然我很愚蠢。 JScrollPane / JLabel涵盖了JPanel,它是唯一具有MouseMotionListener的组件。解决方案是添加单行image.addMouseMotionListener(this);

我想到并尝试了至少三个小时的不同解决方案。这是一个爱好项目,所以没有时间限制,但是我现在感到愚蠢。

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