有没有办法停止MouseListener?

时间:2013-12-08 04:45:55

标签: java awt mouselistener

好的,我正在尝试做的是通过点击放置图像。我有一个布尔值,我设置它以便在按下鼠标时它是真的,在它被释放时它是假的。然后我有以下代码:

if (place == true){
                msex = MouseInfo.getPointerInfo().getLocation().x;
                msey = MouseInfo.getPointerInfo().getLocation().y;
            }

并在主屏幕上显示:

if (place == true){
            d.drawImage(twilightblock,msex - 45,msey - 85,this);
        }

然而,当我尝试它时,我点击并显示,但当我释放鼠标按钮时它会消失。它也可以用鼠标移动而不是呆在一个地方。我想知道,有没有办法在按下按钮后立即停止MouseListener?如果是这样,那将是完美的。 :d

1 个答案:

答案 0 :(得分:0)

使用MouseAdapter并选择适当的方法:http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseAdapter.html

  1. onClick on image(第一个组件)
  2. 将图像的数据或引用存储在临时结构/对象中
  3. onCLick on second component
  4. 从tempprary结构/对象访问图像的数据并将其应用于第二个组件
  5. 从第一个组件中删除图像
  6. 回答你的评论,这是你能做的高级支架:

    public static void main() {
        SomeOtherObject so; // use to store app data
        // create possibly many components of type B
        JComponentB compB = new JComponentB(so);
        JComponentA compA = new JComponentA(so);
        // add them to your JFrame, or other component
    }
    
    import java.awt.event.MouseAdapter;
    class JComponentA  extends MouseAdapter {
        String imagePath;
        Image myImage;
    
        public JComponentA(SomeOtherObject so) { };
    
        public void mouseClicked(MouseEvent e) {
            this.imagePath = so.getImagePath;
            // display new image, or maybe swap images
        }
    }
    
    import java.awt.event.MouseAdapter;
    class JComponentB extends MouseAdapter {
        String imagePath;
        Image myImage;
    
        public JComponentB(SomeOtherObject so) { };
    
        public void mouseClicked(MouseEvent e) {
            so.setImagePath(this.imagePath);
            // delete image, or maybe do a swap (that requires two strings in SomeOtherObject)
        }
    }