本文介绍了当我向 Jpanel 添加按钮时,KeyListener 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现,当我写pnlMap.add(map[i][j])"时,keylistener 不起作用.map 是 JButton 的集合,pnlMap 是 JPanel.

I found that, when I write "pnlMap.add(map[i][j])" keylistener won't work. map is set of JButton, pnlMap is JPanel.

公共游戏(玩家玩家){

public Game(Player player){

    initComponents();
    this.player = player;
    loadPlayerInfo();
    ImageIcon icon = new ImageIcon("images/items/sword_advanced.png");
    this.setIconImage(icon.getImage());
    addKeyListener(this);
    map = new Square2[20][20];
    for (int j = 0; j < 20; j++) {
        for (int i = 0; i < 20; i++) {
            map[i][j] = new Square2();
            pnlMap.add(map[i][j]);
        }
    }
}

推荐答案

为了使 KeyListener 能够工作,它注册到的组件必须是可聚焦的并且具有键盘焦点.像 JComponentJPanel 这样的大多数容器在默认情况下是不可聚焦的(在考虑使它们如此之前我会非常小心).这意味着当您添加一个可以接受键盘焦点(并且它接收键盘焦点)的组件时,您的 KeyListener 将不再起作用.

In order for KeyListener to work, the component it is registered to MUST be focusable AND have keyboard focus. Most containers like JComponent and JPanel aren't focusable by default (and I'd be VERY careful before considering making them so). This means that the moment you add a component which can accept keyboard focus (and it receives keyboard focus), your KeyListener will no longer work.

这是我们建议不要使用它的众多原因之一.相反,请使用 Key Bindings API,它允许您确定组件触发绑定所需的焦点级别

This is one of the many reasons we recommend against using it. Instead, make use of the Key Bindings API, which allows you to, among other things, determine the level of focus a component will need in order to trigger the bindings

有关详细信息,请参阅如何使用键绑定

这篇关于当我向 Jpanel 添加按钮时,KeyListener 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-12 03:18