栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JPanel上的KeyListener随机无响应

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JPanel上的KeyListener随机无响应

尝试将JButton添加到“画布” JPanel中,然后按按钮并查看KeyListener发生了什么-
失败是因为JPanel失去了焦点。为了防止这种情况的发生,请改用“键绑定”(请参阅​​上面我的评论中的链接以获取本教程)。例如

import java.awt.event.*;import java.awt.*;import javax.swing.*;@SuppressWarnings("serial")public class Game2 {   private static final String UP = "up";   public static void main(String[] args) {      new Game2();   }   public Game2() {      Jframe window = new Jframe("Press up-arrow key");      window.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);      JPanel canvas = new JPanel();      canvas.setPreferredSize(new Dimension(400, 300));      window.add(canvas);      canvas.add(new JButton(new AbstractAction("Press space-bar") {         public void actionPerformed(ActionEvent e) { System.out.println("Button or space-bar pressed");         }      }));      ActionMap actionMap = canvas.getActionMap();      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;      InputMap inputMap = canvas.getInputMap(condition);      inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), UP);      actionMap.put(UP, new UpAction());      window.pack();      window.setLocationRelativeTo(null);      window.setVisible(true);   }}@SuppressWarnings("serial")class UpAction extends AbstractAction {   @Override   public void actionPerformed(ActionEvent arg0) {      System.out.println("Up Arrow pressed!");   }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570785.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号