java 鼠标左键点击事件
时间: 2023-06-09 20:02:30 浏览: 187
Java中鼠标左键点击事件可通过MouseListener接口中的mouseClicked方法实现。以下为示例代码:
```
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MyMouseListener implements MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) { // 判断左键
System.out.println("鼠标左键点击事件");
}
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
```
可以将该监听器注册到需要监听的组件上,如按钮或面板等:
```
JButton button = new JButton("Click me");
button.addMouseListener(new MyMouseListener());
```
当鼠标左键点击注册了该监听器的组件时,会触发mouseClicked方法中的代码,从而实现对应的操作。
阅读全文