java JFrame - 使用 JComponent 和 MouseListener 进行鼠标单击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15685502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:30:25  来源:igfitidea点击:

JFrame - mouse click using JComponent and MouseListener

javaswingjframejcomponentmouselistener

提问by URL87

Having 2 classes -

有 2 个班级 -

public class MainClass {



  public static void main(String[] args)  {
    JFrame frame = new JFrame();
    ....
    Component mouseClick = new MyComponent()  ; 
    frame.setVisible(true);
}

public class MyComponent extends JComponent implements MouseListener {

    @Override
    public void mouseClicked(MouseEvent arg0) {
        System.out.println("here was a click ! ");

    }
    ...

}

I trying to set on the framea listener for mouse click , but when I run it and then press mouse click nothing happens .

我试图在frame侦听器上设置鼠标单击,但是当我运行它然后按鼠标单击时什么也没有发生。

How to make it work ?

如何使它工作?

回答by Octahedron

In order to receive mouse clicks on your frame, you also need to add mouseClickto the frame's list of MouseListeners. Try adding this line after you create mouseClick:

为了收到您的框架上的鼠标点击,您还需要添加mouseClick到的帧的列表MouseListeners。创建后尝试添加此行mouseClick

frame.addMouseListener((MouseListener) mouseClick);