java中如何处理键盘事件?
2个回答
展开全部
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Example6_12 extends JFrame implements KeyListener
{
JButton b[]=new JButton[3];
int x,y;
public Example6_12()
{
setSize(300,300);
setVisible(true);
setLayout(new FlowLayout());
for(int i=0;i<=2;i++)
{
b[i]=new JButton(" "+i);
b[i].addKeyListener(this);
add(b[i]);
}
validate();
}
public void KeyPressed(KeyEvent e)
{
JButton button=(JButton)e.getSource();
x=button.getBounds().x;
y=button.getBounds().y;
if(e.getKeyCode()==KeyEvent.VK_UP)
{
y=y-2;
if(y<=0)
y=300;
button.setLocation(x,y);
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
y=y+2;
if(y>=300)
y=0;
button.setLocation(x,y);
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
x=x-2;
if(x<=0)
x=300;
button.setLocation(x,y);
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
x=x+2;
if(x>=300)
x=0;
button.setLocation(x,y);
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyPressed(KeyEvent e){}
public static void main(String[] args)
{
Example6_12 win=new Example6_12();
win.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询