awt - Java- Toolkit.getLockingState not updating -
i trying make simple robot program needs know if scroll lock on. read different question , pointed toolkit.getlockingkeystate(). however, method correctly tells whether scoll lock on when started program, refuses update when scroll lock changed. here code:
import java.awt.toolkit; import java.awt.event.keyevent; /** * @author luke senseney * */ public class mouse { /** * @param args */ public static void main(string[] args) { toolkit t=toolkit.getdefaulttoolkit(); while(true) { t.sync(); system.out.println(t.getlockingkeystate(keyevent.vk_num_lock)); try { thread.sleep(1000); }catch(interruptedexception e) { e.printstacktrace(); } } } }
this version works advertised. expect difference code requests state within event dispatch thread (though cannot explain why case).
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.emptyborder; public class checklockingstate { private jcomponent ui = null; checklockingstate() { initui(); } public void initui() { if (ui != null) { return; } ui = new jpanel(new borderlayout(4, 4)); ui.setborder(new emptyborder(4, 4, 4, 4)); final jlabel l = new jlabel("click button check locking state.."); ui.add(l, borderlayout.page_start); final toolkit t = toolkit.getdefaulttoolkit(); actionlistener checkstatelistener = new actionlistener() { @override public void actionperformed(actionevent e) { boolean b = t.getlockingkeystate(keyevent.vk_num_lock); system.out.println(b); l.settext("" + b); } }; jbutton b = new jbutton("check locking state"); b.addactionlistener(checkstatelistener); ui.add(b); } public jcomponent getui() { return ui; } public static void main(string[] args) { runnable r = new runnable() { @override public void run() { try { uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname()); } catch (exception usedefault) { } checklockingstate o = new checklockingstate(); jframe f = new jframe(o.getclass().getsimplename()); f.setdefaultcloseoperation(jframe.dispose_on_close); f.setlocationbyplatform(true); f.setcontentpane(o.getui()); f.pack(); f.setminimumsize(f.getsize()); f.setvisible(true); } }; swingutilities.invokelater(r); } }
Comments
Post a Comment