mousePressed()无效 [英] mousePressed() not working

查看:253
本文介绍了mousePressed()无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了很多但无济于事。我没有得到点击鼠标的坐标。有人请帮助我

I have tried a lot but to no avail. I am not getting the co-ordinates at which the mouse was clicked. Someone please help me

import java.awt.*;
import java.awt.event.*;

public class MyMouseClick extends Frame 
{
    int x=0,y=0;
    Label lbl1;
    
    MyMouseClick()
    {
        super("Mouse Click Event");
        setSize(300,300);
        setVisible(true);
        lbl1=new Label("Lable");
        add(lbl1,BorderLayout.CENTER);
        
        addMouseListener(new MouseAdapter()
                                            {
                                              @Override
                                              public void mousePressed(MouseEvent me)
                                              {
                                                  x=me.getX();
                                                  y=me.getY();
                                                  lbl1.setText("You pressed as "+x+","+y);
                                              }
                                            });
        addWindowListener(new WindowAdapter()
                                            {
                                              @Override
                                              public void windowClosing(WindowEvent me)
                                              {
                                                 setVisible(false);
                                                 System.exit(0);
                                              }
                                            });
    }
    
    public static void main(String args[])
    {
        new  MyMouseClick();
    }
}

已添加代码块[/ Edit]

Code block added[/Edit]

推荐答案

您已添加标签框架并将mouselistener添加到框架中。但是你添加的标签覆盖了整个框架,这就是你想到的原因,你点击框架,实际上你点击了标签,虽然标签没有mouselistener,所以你不能接收任何事件。要测试它,请更改以下内容:



You have added a label into the frame and add the mouselistener into the frame. But what happened the label you added cover the total frame and that is the reason when you thought, you are clicking on the frame , actually you clicked on the label and though the label has no mouselistener so you can''t receive any event. To test it change the following things :

lbl1.addMouseListener(new MouseAdapter(){.....});


这篇关于mousePressed()无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆