键盘事件
Class KeyEvent
java.lang.Object
java.util.EventObject
java.awt.AWTEvent
java.awt.event.ComponentEvent
java.awt.event.InputEvent
java.awt.event.KeyEvent
KeyEvent类 键盘监听类,KeyListener接口也可实现处理事件监听
KeyListener接口有3个抽象方法,分为不同的敲击方式
keyTyped(KeyEvent e); 点击
KeyPressed(keyEvent e); 被按下(未松也触发)
KeyReleased(keyEvent e); 松开释放
方法自查API
注意:KeyEvent类中以“VK_”为前缀的静态常量代表键盘的keyCode(键盘按键
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyEventTest extends JFrame {
private JTextField jtf = new JTextField(3);
private JLabel jl = new JLabel("H");
private Container container = getContentPane();
public KeyEventTest(){
setBounds(400, 300, 90, 80);
setDefaultCloseOperation(3);
jtf.setFont(new Font("微软雅黑",Font.PLAIN,16));
jl.setFont(new Font("微软雅黑",Font.PLAIN,16));
//窗体流布局
container.setLayout(new FlowLayout());
//添加组件
container.add(jtf);
container.add(jl);
jtf.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
System.out.println("点击了键盘");
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyText(e.getKeyCode()));
}
@Override
public void keyReleased(KeyEvent e) {
jtf.setText("");
jl.setText(e.getKeyText(e.getKeyCode()));
}
});
setVisible(true);
}
public static void main(String[] args) {
new KeyEventTest();
}
}
![](https://sanscan12.gitee.io/blogimg/Content/Java/Java35.gif)
鼠标事件
Class MouseEvent
java.lang.Object
java.util.EventObject
java.awt.AWTEvent
java.awt.event.ComponentEvent
java.awt.event.InputEvent
java.awt.event.MouseEvent
MouseEvent类 键盘监听类,MouseListener接口也可实现处理事件监听
MouseListener接口有5个抽象方法,分为不同的触发方式
mouseEntered(MouseEvent e); 鼠标移入组件触发\
mousePressed(MouseEvent e); 鼠标按下触发
mouseReleased(MouseEvent e); 鼠标释放触发
mouseClicked(MouseEvent e); 鼠标单击触发
mouseExited(MouseEvent e); 鼠标移出组件触发
方法自查API
MouseEvent类静态常量
静态常量 | 值 | 键 |
---|---|---|
BUTTON1 | 1 | 鼠标左键 |
BUTTON2 | 2 | 鼠标滚轮 |
BUTTON3 | 3 | 鼠标右键 |
import javax.swing.*;
import java.awt.*;
import java.awt