简体   繁体   中英

Puzzle game with KeyListener using Java GUI?

I want to implement key listener on my puzzle game. i have done it with action listener but now want to move on with key listener.

My logic for action listener was that:

when a specific button is clicked it checks if is adjacent button's icon is null if it is null then their icons will be swapped Now, how can I do it with key listener? Thank you.

if( b1==e.getSource()){

    if(b2.getIcon()==null){
        b2.setIcon(b1.getIcon());
        b1.setIcon(null);
    }
    else if(b5.getIcon()==null){
        b5.setIcon(b1.getIcon());

        b1.setIcon(null);   
    }
 }

You tell us that you have implemented a KeyListener but it's not working. Without code, all we can do is guess, so here's mine:

  • KeyListeners require focus to work, and so if your GUI has any components that steal the focus, such as JButtons, all JTextComponents such as JTextArea or JTextField, JComboBoxes, JLists,... then your KeyListener won't work.
  • One kludge is to force the component with the KeyListener to have the focus and to greedily hold on to the focus. This is not advisable since it will force your program to behave abnormally since most users expect buttons to have and retain focus when pressed, and text components won't work if they're not allowed focus.
  • Again, often the best solution is to use Key Bindings since these can work without requiring focus and are a cleaner way to capture keystrokes. Please look at the Key Bindings Tutorial and then have a look at my example code for using Key Bindings here and here .

Again for better and more specific help, then please tell us more of the details and show us your pertinent code, preferably as a minimal example program or MCVE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM