Java 通過監聽鍵盤和鼠標事件可以實現一些有趣的功能。鍵盤事件包括按下和釋放按鍵,而鼠標事件包括按下和釋放鼠標按鈕、單擊和雙擊等。以下是通過 Java 監聽鍵盤和鼠標的方式。
1. 監聽鍵盤事件
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class KeyboardListener extends JFrame implements KeyListener {
public KeyboardListener() {
addKeyListener(this);
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("鍵盤按下:" + e.getKeyChar());
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("鍵盤釋放:" + e.getKeyChar());
}
@Override
public void keyTyped(KeyEvent e) {
System.out.println("鍵盤輸入:" + e.getKeyChar());
}
public static void main(String[] args) {
KeyboardListener kl = new KeyboardListener();
kl.setSize(200,200);
kl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
kl.setVisible(true);
}
}
2. 監聽鼠標事件
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
public class MouseListener extends JFrame {
public MouseListener() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
System.out.println("鼠標右鍵按下");
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
System.out.println("鼠標右鍵釋放");
}
}
});
}
public static void main(String[] args) {
MouseListener ml = new MouseListener();
ml.setSize(200,200);
ml.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ml.setVisible(true);
}
}
以上就是 Java 監聽鍵盤和鼠標事件的方式。
上一篇ajax 的各種jar包
下一篇asp翻譯php