JAVA-KeyEvent事件响应的处理方式

要求:
界面如图,应用程序可能通过键盘上的方向键(上,下,左,
右) 控制按键分别向对应的方向移动。

在这里插入图片描述
代码:

public class test {
	public static void main(String args[]){
		Win win=new Win();
		win.setTitle("KeyEvent事件");
		win.setBounds(20,20,400,350);
	}

}
import java.awt.*;
import javax.swing.*;


public class Win extends JFrame{
	JButton b;
	Police police;
	Win(){
		setLayout(null);
		police=new Police();
		b=new JButton("请按方向键移动");
		police.setJButton(b);
		b.addKeyListener(police);
		b.addFocusListener(police);
		b.requestFocusInWindow();
		b.setBounds(120,100,130,40);
		add(b);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}
	

}
import java.awt.event.*;
import javax.swing.*;
public class Police implements KeyListener,FocusListener  {
	JButton b;
	public void setJButton(JButton b){
		this.b=b;
	}
    public void keyPressed(KeyEvent e) {
    	if(e.getKeyCode()==37){
    		b.setLocation(b.getX()-100,b.getY());//左
    	}
    	if(e.getKeyCode()==39){
    		b.setLocation(b.getX()+130,b.getY());//右
    	}
    	if(e.getKeyCode()==40){
    		b.setLocation(b.getX(),b.getY()+80);//上
    	}
    	if(e.getKeyCode()==38){
    		b.setLocation(b.getX(),b.getY()-100);//下
    	}
    }
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
    public void focusGained(FocusEvent e) {
    }
    public void focusLost(FocusEvent e){}
}

发布了15 篇原创文章 · 获赞 1 · 访问量 324

猜你喜欢

转载自blog.csdn.net/z_mawkish/article/details/105182972