JFrame - mouse click using JComponent and MouseListener

我怕爱的太早我们不能终老 提交于 2019-12-02 08:00:33

问题


Having 2 classes -

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 frame a listener for mouse click , but when I run it and then press mouse click nothing happens .

How to make it work ?


回答1:


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

frame.addMouseListener((MouseListener) mouseClick);


来源:https://stackoverflow.com/questions/15685502/jframe-mouse-click-using-jcomponent-and-mouselistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!