Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

java - KeyListener doesn't work when I add button to 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]); 
        }
    }     
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...