单击时使用 MouseListener 移动图像

Moving an image with MouseListener when CLICKED

我正在尝试在用户按下 clicks/holds 鼠标按钮时使用鼠标移动图像。当用户按住鼠标时(它用鼠标实时更新),我设法做到了这一点,但是,当我点击图像时,图像将其位置调整到更新区域,这不是我想要的想要它做。我希望图像在被点击时移动的唯一时间是用户再次点击,第二次。因此,假设如果用户单击位于 (0,0) 的图像,如果用户再次单击屏幕上的其他位置,则该位置现在位于 (x,y)。

这是我的资料:

@Override
public void mouseClicked(MouseEvent e) {

    clickCount++;
    if(clickCount % 2 == 0){
        p.setLocation(e.getX(), e.getY());//p is just a panel that contains the img
        repaint();
    }
    System.out.println("mouse clicked...");

}

更新代码:

public void mouseClicked(MouseEvent e) {

    Object o = e.getSource();
    if(o instanceof JPanel)
        clickCount++;

    if(clickCount % 2 == 0 && clickCount != 0){
        p.setLocation(e.getX(), e.getY());
        repaint();
    }
    System.out.println("mouse clicked " + clickCount + " times");   
}

这更接近工作,但是,如果您单击屏幕上的任意位置(在 clickCount % 2 == 0 之后),图像将会移动。

调用 mouseClicked 时,确定之前是否单击过某些内容,如果是,则将对象移动到当前位置,如果不是,则检查用户是否单击了可移动的内容,并且将其分配给一个变量(您稍后会用它来检查)。

移动对象后,将引用设置为 null

private JPanel clicked;

@Override
public void mouseClicked(MouseEvent e) {

    if (clicked != null) {
        clicked.setLocation(e.getX(), e.getY());
        clicked = null;
    } else {
        // Figure out if any panel was clicked and assign
        // a reference to clicked
    }

}

可运行示例...

所以,听起来你想同时支持点击和拖动重定位,这有点……困难,因为两者所需的鼠标操作不同,所以你需要监视多个状态并使关于您可能处于的状态的决定,例如...

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MouseTest {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(null);
            JPanel panel = new JPanel();
            panel.setBackground(Color.RED);
            panel.setSize(50, 50);
            panel.setLocation(50, 50);
            add(panel);

            MouseAdapter ma = new MouseAdapter() {
                private Point offset;
                private Point clickPoint;
                private JPanel clickedPanel;

                @Override
                public void mousePressed(MouseEvent e) {
                    // Get the current clickPoint, this is used to determine if the
                    // mouseRelease event was part of a drag operation or not
                    clickPoint = e.getPoint();
                    // Determine if there is currently a selected panel or nor
                    if (clickedPanel != null) {
                        // Move the selected panel to a new location
                        moveSelectedPanelTo(e.getPoint());
                        // Reset all the other stuff we might other was have set eailer
                        offset = null;
                        clickedPanel = null;
                    } else {
                        // Other wise, find which component was clicked
                        findClickedComponent(e.getPoint());
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    // Check to see if the current point is equal to the clickedPoint
                    // or not.  If it is, then this is part of a "clicked" operation
                    // meaning that the selected panel should remain "selected", otherwise
                    // it's part of drag operation and should be discarded
                    if (!e.getPoint().equals(clickPoint)) {
                        clickedPanel = null;
                    }
                    clickPoint = null;
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    // Drag the selected component to a new location...
                    if (clickedPanel != null) {
                        moveSelectedPanelTo(e.getPoint());
                    }
                }

                protected void findClickedComponent(Point p) {
                    Component comp = getComponentAt(p);
                    if (comp instanceof JPanel && !comp.equals(TestPane.this)) {
                        clickedPanel = (JPanel) comp;
                        int x = p.x - clickedPanel.getLocation().x;
                        int y = p.y - clickedPanel.getLocation().y;
                        offset = new Point(x, y);
                    }

                }

                private void moveSelectedPanelTo(Point p) {
                    if (clickedPanel != null) {
                        int x = p.x - offset.x;
                        int y = p.y - offset.y;
                        System.out.println(x + "x" + y);
                        clickedPanel.setLocation(x, y);
                    }
                }

            };

            addMouseListener(ma);
            addMouseMotionListener(ma);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}