其实监听键盘事件和简单,键盘也就这3个事件keyTyped, keyReleased, keyPressed
下面我们就监听一个CTRL+C组合键好了。
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Gui10 extends Panel {
public Gui10(String title) {
Frame frame = new Frame(title);
frame.setSize(200, 400);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
init();
frame.add(this);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private void init() {
final TextArea textArea = new TextArea(10, 20);
textArea.setBackground(Color.CYAN);
textArea.setText("test");
this.add(textArea);
textArea.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("arg0.getModifiers()=" + e.getModifiers());
System.out.println("arg0.getKeyCode()=" + e.getKeyCode());
// CTRL+C按下
if (e.getModifiers() == 2 && e.getKeyCode() == 67) {
System.out.println("CTRL+C......");
}
}
@Override
public void keyPressed(KeyEvent e) {
}
});
}
public static void main(String[] args) {
new Gui10("demo");
}
}
直接运行,鼠标点进textarea,按CTRL+C看看应该会打印:
arg0.getModifiers()=2
arg0.getKeyCode()=67
CTRL+C......
arg0.getModifiers()=0
arg0.getKeyCode()=17