JPanel上的addKeyListener方法没有起作用,为什么?

waq12 2006-09-28 10:39:38
JFrame 内有 JPanel。
在 JPanel 中进行 addKeyListener 实现的代码不能被键盘动作触发;
而在 JFrame 中进行 addKeyListener 实现的代码却能被键盘动作触发;
直接在 JFrame 中用:
KeyListener[] _arKL = jPane.getKeyListeners();
for (int i = 0; i < _arKL.length; i++) {
this.addKeyListener(_arKL[i]);
}
即可将事件传递给 JPanel 中的实现代码,不过觉此法肤浅故请教Swing先人指点一二,不胜感激!
还查阅了部分资料,不知道是不是焦点问题?
...全文
1185 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
waq12 2007-02-01
  • 打赏
  • 举报
回复
dejinzhao()
是对的,不过之前我自己也已经用这个方法解决这个问题了,过来结贴的。呵呵!不过还是要感谢下。
waq12 2007-01-21
  • 打赏
  • 举报
回复
lbfhappy(千里冰封)
> 事件注册到顶层控件是可以响应键盘事件的,但是如果此时控制的控件设置为没有焦点而又存在其他的带焦点的控件的话就会让此键盘事件失效。
dejinzhao 2007-01-21
  • 打赏
  • 举报
回复
对java不够了解、需努力了!!!不要直接向panel中添加键盘事件(add方法)、应该用类似下面的两种方法:
1、
KeyStroke shiftup = KeyStroke.getKeyStroke(KeyEvent.VK_UP,java.awt.event.InputEvent.SHIFT_DOWN_MASK);
panel.registerKeyboardAction(this,"shiftup",shiftup,JComponent.WHEN_IN_FOCUSED_WINDOW);
2、registerKeyboardAction()已经是不在被建议使用的方法。建议使用
getInputMap().put(aKeyStroke,aCommand)和getActionMap().put(aCommand,aAction)来组合代替
Moon 2007-01-21
  • 打赏
  • 举报
回复
addKeyListener了没?
waq12 2006-11-26
  • 打赏
  • 举报
回复
嗯,键盘事件只能注册在顶级窗口也是很合理的,其它的内部控件键盘事件触发就只能通过快捷键或其它的方式来进行了吗?
butnet 2006-11-06
  • 打赏
  • 举报
回复
public void addKeyListener(KeyListener l)

添加指定的按键侦听器,接收此组件发出的按键事件。如果 l 为 null,则不会抛出异常并且不执行操作。
千里冰封820 2006-11-06
  • 打赏
  • 举报
回复
是 的,像键盘事件必须注册到顶级窗口类才有效,比如JFrame
waq12 2006-11-06
  • 打赏
  • 举报
回复
郁闷
zxh2208180 2006-09-29
  • 打赏
  • 举报
回复
up contentPane
/*主框架类*/ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyJFrame extends JFrame { private static final long serialVersionUID = 1L; public MyJFrame()//构造方法 { init();//自定义方法1 setVisible(true);//可见 } private void init()//自定义方法 { Toolkit tlk = Toolkit.getDefaultToolkit(); Image tittle = tlk.getImage("pho/最小化.png");//添加最小化图标 setIconImage(tittle); setUndecorated(true);//不启用标题栏 MyJPanel jpanel=new MyJPanel(); setContentPane(jpanel);//作用类似于add() setSize(1200,700);//设置窗口大小 setResizable(false);//不可改变大小 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭 setLocationRelativeTo(null);//窗口出现在桌面中间 /*******把鼠标隐藏*****/ Toolkit tool = Toolkit.getDefaultToolkit(); Image mouse=tool.getImage("pho/mouse.png");//给鼠标加一张透明的图片 Cursor cursor = tool.createCustomCursor(mouse,new Point(),null); setCursor(cursor); addKeyListener((KeyListener) new MyKeyAdapter());//设置键盘监听,用来退出游戏 } private class MyKeyAdapter extends KeyAdapter//键盘监听适配器 { public void keyPressed(KeyEvent e) { super.keyPressed(e); int event = e.getKeyCode();//接受键盘事件 if(event == KeyEvent.VK_ESCAPE)//按ESC退出 { int result = JOptionPane.showConfirmDialog(null, "是否退出游戏", "提示", JOptionPane.OK_CANCEL_OPTION); if(result == JOptionPane.OK_OPTION)//点击确定退出 { System.exit(0); } } } } }
package com; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.WindowConstants; public class Caculator extends JFrame implements ActionListener,KeyListener{ /** * */ private static final long serialVersionUID = 5204982079673572494L; private JTextField tf=new JTextField(); private float x=0; private float y=0; private int code=0; private boolean enable; private boolean first; private String str=""; public Caculator(){ Container ct=this.getContentPane(); this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); tf.setHorizontalAlignment(JTextField.RIGHT); //tf.setText("0"); enable=true; first=true; ct.add(tf,BorderLayout.NORTH); JPanel panel=new JPanel(); panel.setLayout(new GridLayout(4,4)); this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ if(JOptionPane.YES_OPTION==JOptionPane.showConfirmDialog(Caculator.this,"确定要关闭程序吗?","提示",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE)){ e.getWindow().setVisible(false); e.getWindow().dispose(); System.exit(0); } } }); Button btn=null; btn=new Button("1"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("2"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("3"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("+"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("4"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("5"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("6"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("-"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("7"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("8"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("9"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("*"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("0"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("."); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("/"); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); btn=new Button("="); panel.add(btn); btn.addActionListener(this); btn.addKeyListener(this); this.add(panel,BorderLayout.CENTER); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Caculator mainframe=new Caculator(); mainframe.setTitle("testing Caculator"); mainframe.setSize(400,400); mainframe.setVisible(true); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getActionCommand()=="+"){ x= Float.parseFloat(tf.getText()); code=0; this.tf.setText(""); } if(e.getActionCommand()=="-"){ x= Float.parseFloat(tf.getText()); code=1; this.tf.setText(""); } if(e.getActionCommand()=="*"){ x= Float.parseFloat(tf.getText()); code=2; this.tf.setText(""); } if(e.getActionCommand()=="/"){ x= Float.parseFloat(tf.getText()); code=3; this.tf.setText(""); } if(e.getActionCommand()!="+"&&e.getActionCommand()!="-"&&e.getActionCommand()!="*"&&e.getActionCommand()!="/"&&e.getActionCommand()!="="){ if(enable){ if(first){ System.out.println("haha"); tf.setText(e.getActionCommand()); first=false; } else { tf.setText(tf.getText()+e.getActionCommand()); } } else { tf.setText(e.getActionCommand()); enable=true; } } if(e.getActionCommand()=="="){ switch(code){ case 0: y=x+Float.parseFloat(this.tf.getText()); tf.setText(Float.toString(y)); enable=false; break; case 1: y=x-Float.parseFloat(this.tf.getText()); tf.setText(Float.toString(y)); enable=false; break; case 2: y=x*Float.parseFloat(this.tf.getText()); tf.setText(Float.toString(y)); enable=false; break; case 3: y=x/Float.parseFloat(this.tf.getText()); tf.setText(Float.toString(y)); enable=false; break; } } } public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub if(e.getKeyChar()=='+'){ x= Float.parseFloat(tf.getText()); code=0; this.tf.setText(""); } if(e.getKeyChar()=='-'){ x= Float.parseFloat(tf.getText()); code=1; this.tf.setText(""); } if(e.getKeyChar()=='*'){ x= Float.parseFloat(tf.getText()); code=2; this.tf.setText(""); } if(e.getKeyChar()=='/'){ x= Float.parseFloat(tf.getText()); code=3; this.tf.setText(""); } if(e.getKeyChar()=='1'||e.getKeyChar()=='2'||e.getKeyChar()=='3'||e.getKeyChar()=='0' ||e.getKeyChar()=='4'||e.getKeyChar()=='5'||e.getKeyChar()=='6'||e.getKeyChar()=='.' ||e.getKeyChar()=='7'||e.getKeyChar()=='8'||e.getKeyChar()=='9'){ System.out.println("hai"); if(enable){ if(first){ System.out.println("hehe"); str=Character.toString(e.getKeyChar()); tf.setText(str); first=false; } else { str=Character.toString(e.getKeyChar()); tf.setText(tf.getText()+str); } } else { str=Character.toString(e.getKeyChar()); tf.setText(str); enable=true; } } if(e.getKeyCode()==KeyEvent.VK_ENTER){ switch(code){ case 0: y=x+Float.parseFloat(this.tf.getText()); tf.setText(Float.toString(y)); enable=false; break; case 1: y=x-Float.parseFloat(this.tf.getText()); tf.setText(Float.toString(y)); enable=false; break; case 2: y=x*Float.parseFloat(this.tf.getText()); tf.setText(Float.toString(y)); enable=false; break; case 3: y=x/Float.parseFloat(this.tf.getText()); tf.setText(Float.toString(y)); enable=false; break; } } } public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }
public class GreedSnake implements KeyListener { JFrame mainFrame; Canvas paintCanvas; JLabel labelScore;//计分牌 SnakeModel snakeModel=null;// 蛇 public static final int canvasWidth=200; public static final int canvasHeight=300; public static final int nodeWidth=10; public static final int nodeHeight=10; //---------------------------------------------------------------------- //GreedSnake():初始化游戏界面 //---------------------------------------------------------------------- public GreedSnake() { //设置界面元素 mainFrame=new JFrame("GreedSnake"); Container cp=mainFrame.getContentPane(); labelScore=new JLabel("Score:"); cp.add(labelScore,BorderLayout.NORTH); paintCanvas=new Canvas(); paintCanvas.setSize(canvasWidth+1,canvasHeight+1); paintCanvas.addKeyListener(this); cp.add(paintCanvas,BorderLayout.CENTER); JPanel panelButtom=new JPanel(); panelButtom.setLayout(new BorderLayout()); JLabel labelHelp;// 帮助信息 labelHelp=new JLabel("PageUp, PageDown for speed;",JLabel.CENTER); panelButtom.add(labelHelp,BorderLayout.NORTH); labelHelp=new JLabel("ENTER or R or S for start;",JLabel.CENTER); panelButtom.add(labelHelp,BorderLayout.CENTER); labelHelp=new JLabel("SPACE or P for pause",JLabel.CENTER); panelButtom.add(labelHelp,BorderLayout.SOUTH); cp.add(panelButtom,BorderLayout.SOUTH); mainFrame.addKeyListener(this); mainFrame.pack(); mainFrame.setResizable(false); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setVisible(true); begin(); 。 。 。 。 。 。 。
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class snate extends JFrame implements KeyListener,Runnable { JLabel j; Canvas j1; public static final int canvasWidth = 200; public static final int canvasHeight = 300; public static final int nodeWidth = 10; public static final int nodeHeight = 10; //SnakeModel se=null; //222222 // boolean[][] matrix; LinkedList nodeArray = new LinkedList();//表 Node food;//节点 int maxX; int maxY; int direction = 2; boolean running = false; int timeInterval = 200; double speedChangeRate = 0.75; boolean paused = false; int score = 0; int countMove = 0; // UP and DOWN should be even // RIGHT and LEFT should be odd public static final int UP = 2; public static final int DOWN = 4; public static final int LEFT = 1; public static final int RIGHT = 3; snate() { super(); //setSize(500,400); Container c=getContentPane(); j=new JLabel("Score:"); c.add(j,BorderLayout.NORTH); j1=new Canvas(); j1.setSize(canvasWidth+1,canvasHeight+1); j1.addKeyListener(this); c.add(j1,BorderLayout.CENTER); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); JLabel j2; j2 = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER); p1.add(j2, BorderLayout.NORTH); j2 = new JLabel("ENTER or R or S for start;", JLabel.CENTER); p1.add(j2, BorderLayout.CENTER); j2 = new JLabel("SPACE or P for pause",JLabel.CENTER); p1.add(j2, BorderLayout.SOUTH); c.add(p1,BorderLayout.SOUTH); addKeyListener(this); pack(); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); // begin(); // //2222222 // this.gs = gs; this.maxX = maxX; this.maxY = maxY; // initial matirx matrix = new boolean[maxX][]; for(int i=0; i 20 ? 10 : maxX/2; for(int i = 0; i < initArrayLength; ++i){ int x = maxX/2+i; int y = maxY/2; nodeArray.addLast(new Node(x, y)); matrix[x][y] = true; } food = createFood(); matrix[food.x][food.y] = true; } public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_UP) { //se.changeDirection(SnakeModel.UP); } if(e.getKeyCode()==KeyEvent.VK_DOWN) { //se.changeDirection(SnakeModel.DOWN); } if(e.getKeyCode()==KeyEvent.VK_LEFT) { //se.changeDirection(SnakeModel.LEFT); } if(e.getKeyCode()==KeyEvent.VK_RIGHT) { //se.changeDirection(SnakeModel.RIGHT); } if(e.getKeyCode()==KeyEvent.VK_R||e.getKeyCode()==KeyEvent.VK_S||e.getKeyCode()==KeyEvent.VK_ENTER) { } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void repaint() { Graphics g = j1.getGraphics(); //背景 g.setColor(Color.red); g.fillRect(0,0,canvasWidth,canvasHeight); //蛇 //g.setColor(Color.BLUE); } public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(10,10,10,10); } // //222222 // public void changeDirection(int newDirection){ if (direction % 2 != newDirection % 2){ direction = newDirection; } } public boolean moveOn(){ Node n = (Node)nodeArray.getFirst(); int x = n.x; int y = n.y; switch(direction){ case UP: y--; break; case DOWN: y++; break; case LEFT: x--; break; case RIGHT: x++; break; } if ((0 <= x && x < maxX) && (0 <= y && y < maxY)){ if (matrix[x][y]){ if(x == food.x && y == food.y){ nodeArray.addFirst(food); int scoreGet = (10000 - 200 * countMove) / timeInterval; score += scoreGet > 0? scoreGet : 10; countMove = 0; food = createFood(); matrix[food.x][food.y] = true; return true; } else return false; } else{ nodeArray.addFirst(new Node(x,y)); matrix[x][y] = true; n = (Node)nodeArray.removeLast(); matrix[n.x][n.y] = false; countMove++; return true; } } return false; } public void run(){ running = true; while (running){ try{ Thread.sleep(timeInterval); } catch(Exception e){ break; } if(!paused){ if (moveOn()){ gs.repaint(); } else{ JOptionPane.showMessageDialog( null, "you failed", "Game Over", JOptionPane.INFORMATION_MESSAGE); break; } } } running = false; } private Node createFood(){ int x = 0; int y = 0; do{ Random r = new Random(); x = r.nextInt(maxX); y = r.nextInt(maxY); }while(matrix[x][y]); return new Node(x,y); } public void speedUp(){ timeInterval *= speedChangeRate; } public void speedDown(){ timeInterval /= speedChangeRate; } public void changePauseState(){ paused = !paused; } public String toString(){ String result = ""; for(int i=0; i

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧