JFrame - 使用 JComponent 和 MouseListener 进行鼠标单击
有 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 ! ");
}
...
}
我试图在 frame
上设置鼠标单击的侦听器,但是当我运行它然后按下鼠标单击时没有任何反应.
I trying to set on the frame
a listener for mouse click , but when I run it and then press mouse click nothing happens .
如何使它工作?
推荐答案
为了在你的框架上接收鼠标点击,你还需要将 mouseClick
添加到框架的 MouseListeners 列表中/代码>.创建
mouseClick
后尝试添加此行:
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);
相关文章