KeyListener doesn't work when I add button to Jpanel

前端 未结 1 1461
无人共我
无人共我 2020-12-12 03:02

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) {



        
相关标签:
1条回答
  • 2020-12-12 03:17

    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.

    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

    See How to Use Key Bindings for more details

    0 讨论(0)
提交回复
热议问题