Java Swing - JDialog default focus -
i have found in internet such info:
"when jdialog (or jframe matter) made visible, focus placed on first focusable component default."
let's consider such code:
public class mydialog extends jdialog{ // dialog's components: private jlabel dialoglabel1 = new jlabel("hello"); private jlabel dialoglabel2 = new jlabel("message"); private jbutton dialogbtn = new jbutton("sample btn text"); public mydialog(jframe parent, string title, modalitytype modality){ super(parent, title, modality); dialogbtn.setname("button"); // dialoglabel1.setname("label1"); // - setting names dialoglabel2.setname("label2"); // settitle(title); setmodalitytype(modality); setsize(300, 100); setlocation(200, 200); // adding comps contentpane getcontentpane().add(dialoglabel1, borderlayout.page_start); getcontentpane().add(dialogbtn, borderlayout.center); getcontentpane().add(dialoglabel2, borderlayout.page_end); pack(); } public void showdialog(){ setvisible(true); listcomps(rootpane.getcomponents()); setdefaultcloseoperation(dispose_on_close); } /* * itereates through subcomps recursively , displays relevant info * output form: componentname | isfocusable | hasfocus */ private void listcomps(component[] comps){ if(comps.length == 0) return; for(component c : comps){ jcomponent jc = (jcomponent)c; system.out.println(jc.getname() + " | " + jc.isfocusable() +" | " + jc.hasfocus()); listcomps(jc.getcomponents()); } } public static void main(string[] args) { final jframe frame = new jframe(); frame.setpreferredsize(new dimension(300, 400)); frame.setvisible(true); jbutton btn = new jbutton("show dialog"); btn.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { mydialog dialog = new mydialog(frame, "sample title", modalitytype.application_modal); dialog.showdialog(); } }); frame.add(btn, borderlayout.center); frame.pack(); } }
output is: run:
null.glasspane | true | false null.layeredpane | true | false null.contentpane | true | false label1 | true | false button | true | true label2 | true | false
why focus set jbutton?? not first focusable component! when i've removed jbutton, focus wasn't gained component. why? compos focusable default...
it not first focusable component! when i've removed jbutton, focus wasn't gained component. why? compos focusable default.
to answer why: it's decision of focustraversalpolicy, particularly accept(..) in defaultfocustraversalpolicy falls dummy nullcomponentpeer (which not focusable default, doesn't exist :-)
from comment, looks real question might "how implement keybindings if rootpane has no focusable children" - if so, options are
- use rootpane's componentinputmap, when_in_focused_window
- force rootpane focusable (probably best doing if there no focusable children)
Comments
Post a Comment