Java 键盘监听 KeyListener 无法监听的解决办法

时间:2024-04-02 08:01:20

最近在学JAVA,里面有一个事件监听,想做监听但是一直做不好。从网上查了资料才发现原来实现了KeyListener接口以后 还需要使用addKeyListener(this)绑定一下才可以


package com.jianting.liutong;

import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JPanel;

public class Action extends Frame implements KeyListener {

	/**
	 * @param args
	 */
	Button b1;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Action action=new Action();
		
	}
	public Action(){
		Frame frame=new Frame("事件监听");
		//b1=new Button("按下");
		addKeyListener(this);//**绑定监听 没有这行 不会有任何监听**
		this.setSize(500, 500);
		this.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){  
	          System.exit(0);  
		
		}});
	
		
		this.setVisible(true);
		
		
	}
	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		
		if(e.getKeyCode()==KeyEvent.VK_E){
			System.out.println("按下E键");
			
		}
		
	}
	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

}

Java 键盘监听 KeyListener 无法监听的解决办法