Piumi Wandana
Piumi Wandana

Reputation: 228

java keyevent not work as desired

i'm going to create simple typing game in java.so i created new class wordpanel which extends jpanel .everything works fine expect key-event .when i press a key foreground of all first jlable of panels should be changed to yellow.but i recognize that line not execute because even when i put sout() i didn't get output.i can't find what is the wrong of this code.this my code

public class wordPanel extends JPanel{

    public wordPanel(String word) {

        setOpaque(true);
        char letters[];
        letters = word.toCharArray();
        JLabel lab[]=new JLabel[letters.length];
        setLayout(new GridLayout(1, letters.length));
        for(int i=0;i<letters.length;i++){
            lab[i]=new JLabel(letters[i]+"");
            this.add(lab[i]);
        }

        this.addKeyListener(new java.awt.event.KeyAdapter() {
            @Override
            public void keyPressed(java.awt.event.KeyEvent evt) {
               char ch = evt.getKeyChar();
                   lab[0].setForeground(Color.YELLOW);
                   System.out.println("hey");
            }
        });



    }

} 

this is object creating block

        wordPanel wp1=new wordPanel("hello");
        Dimension d = wp1.getPreferredSize();

        wp1.setBounds(rand.nextInt((500 - 5) + 1) + 5, rand.nextInt((300 - 5) + 1) + 5, d.width, d.height);
        jPanel1.add(wp1);
        revalidate();

Upvotes: 0

Views: 63

Answers (2)

DMP
DMP

Reputation: 1043

Swing is not meant to use KeyListeners, using a Key Binding will work way better, and you don't have to worry about focus as much. See: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

Keybinding is hard, here is a tutorial: http://www.dreamincode.net/forums/topic/245148-java-key-binding-tutorial-and-demo-program/

Upvotes: 4

Naomi
Naomi

Reputation: 5486

I'm guessing that other components on top of the panel receive the key event. Try adding this keylistener to other components.

Upvotes: 1

Related Questions