Sunday, 15 January 2012

java - Focusing a JTextArea in a JTabbedPane -



java - Focusing a JTextArea in a JTabbedPane -

i'm programming chat client in java, i'd have 1 single jdialog open chats. decided work jtabbedpane tab represents single chat.

i set jpanel every tab, contains jtextpane message history , jtextarea users input messages.

for improve usability implemented feature focuses jtextarea when

a new chattab opened the user changes between chattabs (the changelistener of jtabbedpane fires)

i have class chatwindow, extends jdialog , displays jtabbedpane. implemented changelistener.

private jtabbedpane chattabpane; private list<chattab> chattabs; public chatwindow() { chattabs = new arraylist<chattab>(); jpanel chatwindowpanel = new jpanel(new borderlayout()); chattabpane = new jtabbedpane(jtabbedpane.top); chatwindowpanel.add(chattabpane); this.add(chatwindowpanel, borderlayout.center); chattabpane.addchangelistener(new changelistener() { @override public void statechanged(changeevent arg0) { focusinputfield(); } }); } public chattab addchattab(contact contact) { chattab newchattab = new chattab(); chattabs.add(newchattab); chattabpane.addtab(contact.tostring(), null, newchattab.getpanel()); homecoming newchattab; } public void focusinputfield() { (chattab chattab : chattabs) { if(chattab.getpanel() == chattabpane.getselectedcomponent()) { chattab.focusinputfield(); } } } public jtabbedpane getchattabs() { homecoming chattabpane; } }

the method focusinputfield() in class chattab looks this:

public void focusinputfield() { inputfield.requestfocusinwindow(); inputfield.requestfocus(); }

okay, that's focus when tab changed. beside that, have implemented jtextarea focused when new chat tab created. handled in class chatwindowcontroller. there method setchatvisible() phone call when add together new tab chatwindow class:

public void setchatvisible() { if(!chatwindow.isvisible()) { chatwindow.setvisible(true); chatwindow.focusinputfield(); } }

so here problem: focus works when open new chattab. in cases works when user changes tabs, not focus when opened more 1 new chat tab , switch between tabs first time. jtextarea of tab switched not focus. however, when switch 1 time again works time.

does know problem be? i'm out of ideas.

intermittent failure may result wrong synchronization. several thing should examined critically:

verify build gui elements on event dispatch thread (edt).

as certainly using multiple threads, verify updates occur on edt, example.

you can utilize invokelater() order events on edt, shown here.

prefer requestfocusinwindow() on requestfocus(), don't utilize both.

java swing focus jtabbedpane changelistener

No comments:

Post a Comment