swing - java keyevent not work as desired -
i'm going create simple typing game in java.so created new class wordpanel extends jpanel .everything works fine expect key-event .when press key foreground of first jlable of panels should changed yellow.but recognize line not execute because when put sout()
didn't output.i can't find wrong of code.this 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 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();
swing not meant use keylisteners, using key binding work way better, , don't have worry focus much. see: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
keybinding hard, here tutorial: http://www.dreamincode.net/forums/topic/245148-java-key-binding-tutorial-and-demo-program/
Comments
Post a Comment