java - Giving a JPanel priority focus -
i have jpanel using keylistener content pane window; however, there buttons , text fields in grid layout on top of jpanel.
how prioritize focus of jpanel retains focus after editing text or clicking buttons can read key input?
you need add focuslistener
on focuslost
event , request focus again. this:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class jpanelfocus { public static void main(string... argv) throws exception { eventqueue.invokelater(new runnable() { public void run() { jframe f = new jframe("focustest"); jbutton b = new jbutton("button"); final jpanel p = new jpanel(); p.add(b); // here keylistener installed on our jpanel p.addkeylistener(new keyadapter() { public void keytyped(keyevent ev) { system.out.println(ev.getkeychar()); } }); // bit magic - make sure // our jpanel focussed p.addfocuslistener(new focusadapter() { public void focuslost(focusevent ev) { p.requestfocus(); } }); f.getcontentpane().add(p); f.pack(); f.setdefaultcloseoperation(jframe.exit_on_close); f.setvisible(true); // make sure jpanel starts focus p.requestfocus(); } }); } }
this won't work if have fields need keep focus though (you mentioned editable text field). when should key events go text field , when should go jpanel?
Comments
Post a Comment