java 键盘监听为什么没起作用
代码如下,键盘事件注册了,也接收了啊,为什么没反应importjava.awt.BorderLayout;importjava.awt.Color;importjava....
代码如下,键盘事件注册了,也接收了啊,为什么没反应
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class test extends JFrame implements KeyListener{
JPanel p=new JPanel();
JButton b=new JButton();
test(){
p.setLayout(new BorderLayout());
p.add(b,BorderLayout.CENTER);
b.setBackground(Color.red);
this.add(p);
p.add(b);
this.setSize(300, 300);
this.addKeyListener(this);
this.setVisible(true);
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getKeyCode()==KeyEvent.VK_KP_UP){
b.setBackground(Color.black);
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public static void main(String args[]){
new test();
}
} 展开
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class test extends JFrame implements KeyListener{
JPanel p=new JPanel();
JButton b=new JButton();
test(){
p.setLayout(new BorderLayout());
p.add(b,BorderLayout.CENTER);
b.setBackground(Color.red);
this.add(p);
p.add(b);
this.setSize(300, 300);
this.addKeyListener(this);
this.setVisible(true);
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getKeyCode()==KeyEvent.VK_KP_UP){
b.setBackground(Color.black);
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public static void main(String args[]){
new test();
}
} 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询