Key bindings don't work, Java SE, Swing -
i'm trying add shortcut jbutton. i've read how use key bindings tutorial , have read page how use key bindings instead of key listeners , loooooooooooooot of other questions key bindings, haven't found answer me
what i've tried:
public class example extends jframe { public static void main(string args[]) { example example = new example(); } example(){ action action = new action() { @override public object getvalue(string key) { return null; } @override public void putvalue(string key, object value) { } @override public void setenabled(boolean b) { } @override public boolean isenabled() { return false; } @override public void addpropertychangelistener(propertychangelistener listener) { } @override public void removepropertychangelistener(propertychangelistener listener) { } @override public void actionperformed(actionevent e) { system.out.println("hello world!"); } }; jbutton button = new jbutton("hello world!"); button.getinputmap(jcomponent.when_in_focused_window).put(keystroke.getkeystroke("right"), "dosomething"); button.getactionmap().put("dosomething", action); button.addactionlistener(action); add(button); setvisible(true); pack(); } }
i've tried make that: getinputmap(jcomponent.when_in_focused_window).put(keystroke.getkeystroke(keyevent.vk_right, 0, true), "dosmth");
but nothing seems working, doing wrong?
your action
has method called isenabled
you've implemented. javadoc on states:
/** * returns enabled state of <code>action</code>. when enabled, * component associated object active , * able fire object's <code>actionperformed</code> method. * * @return true if <code>action</code> enabled */
since return hardcoded false
, action
never enabled , actionperformed
method never called. problem not binding, it's action itself!
a simple fix change isenabled
return true, or, simpler yet, use abstractaction
in place of action
, , override actionperformed
(abstractaction
kind of "i don't care stuff, give me simplest thing possible 1 method implement!")
Comments
Post a Comment