Java 当 运行 使用 awt Canvas 时,MouseClicked 不工作
Java MouseClicked Not Working When Run With awt Canvas
对于 Java 程序,我需要检测鼠标点击。我导入了 import java.awt.event.*;
。 运行 这个:
public void mouseClicked(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
System.out.println("Click position (X, Y): " + e.getX() + ", " + e.getY());
}
}
当这是 运行 时,我在屏幕上单击时没有得到任何输出。
这是我的 class 开头的样子:
class Drawing extends Canvas implements MouseListener, MouseMotionListener{
我不确定为什么会这样。我在 mac 上,另一个 post (JAVA mouseClicked event doesnt get fired on the Mac) 表明使用 mac 可能有问题。
根据https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
需要将侦听器添加到组件中,例如按钮、面板等
public class MouseEventDemo implements MouseListener {
//where initialization occurs:
//Register for mouse events on blankArea and the panel.
blankArea.addMouseListener(this);
addMouseListener(this);
...
public void mouseClicked(MouseEvent e) {
System.out.println ("Mouse clicked (# of clicks: "
+ e.getClickCount() + ")", e);
}
对于 Java 程序,我需要检测鼠标点击。我导入了 import java.awt.event.*;
。 运行 这个:
public void mouseClicked(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
System.out.println("Click position (X, Y): " + e.getX() + ", " + e.getY());
}
}
当这是 运行 时,我在屏幕上单击时没有得到任何输出。
这是我的 class 开头的样子:
class Drawing extends Canvas implements MouseListener, MouseMotionListener{
我不确定为什么会这样。我在 mac 上,另一个 post (JAVA mouseClicked event doesnt get fired on the Mac) 表明使用 mac 可能有问题。
根据https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
需要将侦听器添加到组件中,例如按钮、面板等
public class MouseEventDemo implements MouseListener {
//where initialization occurs:
//Register for mouse events on blankArea and the panel.
blankArea.addMouseListener(this);
addMouseListener(this);
...
public void mouseClicked(MouseEvent e) {
System.out.println ("Mouse clicked (# of clicks: "
+ e.getClickCount() + ")", e);
}