What I planned to do is when I press Enter key, the application will fire up the button btn_teach, and switch to another tab with textfield focused. Now, when I implement it, it works perfectly if I press the button manually (not pressing Enter). When I actually press Enter, the tab switches back but the text field on that tab is not focused.
tp being JTabbedPane.
My plan is to switch from tab index 1 to tab index 0 and set txt_send focused
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
String say = txt_saypane.getText();
String ans = txt_anspane.getText();
//this.clear();
say = say.replace("\n","");
ans = ans.replace("\n","");
this.talk(this.botTeach(say,ans), false);
tp.setSelectedIndex(0);
}
public void stateChanged(ChangeEvent arg0)
{
// TODO Auto-generated method stub
int sel = tp.getSelectedIndex();
if(sel == 0)
txt_send.requestFocusInWindow();
if(sel == 1)
txt_saypane.requestFocusInWindow();
}
public void keyPressed(KeyEvent e)
{
// TODO Auto-generated method stub
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
if(txt_saypane.isFocusOwner() || txt_anspane.isFocusOwner())
btn_teach.doClick();
}
}
What is the correct way to change focus via KeyListener when switching between tabs in JTabbedPane?
For
JButtonto work on press of theENTERkey you can make thatJButtonto be yourDEFAULT Buttonon frame, instead of usingKeyEvents. You can do this by writing :Writing this line will also make this JButton work on pressing the ENTER key, without you writing the whole KeyListener part for it. Remove the
KeyListenersfrom thisJButton. Once thisJButtonis theDEFAULT Button, now on Pressing theENTERkey, it will do the work that is written inside it’s actionPerformed() method.Don’t use KeyEvents with Swing, that belongs to awt, KeyBinding is what we use with Swing.
Here is one sample program to help your cause :