Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JComboBox and FocusListener

 
mohamed zafer
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello There,
I have added a FocusListener to a JComboBox. But there is no event triggered on either focus gained or focus listened.
Any idea what could be wrong. I am using JDK1.3.1 on win2k
The code I am using is as follows..
public static void main(String[] args)
{
JFrame jf= new JFrame();
Container contentPane = jf.getContentPane();
contentPane.setLayout(new FlowLayout());
JComboBox jc = new JComboBox();
jc.addItem("CEO");
jc.addItem("COO");
jc.addKeyListener(new ComponentKeyListener());
jc.addFocusListener(new ComponentFocusListener());
jf.addKeyListener(new ComponentKeyListener());
jf.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e)
{
System.out.println("Focus gained in Form");
}

public void focusLost(FocusEvent e)
{
JComponent jc = (JComponent)e.getSource();
System.out.println("LOST :Name is"+jc.getName());
}
});
JButton jb = new JButton("Check it out");
jb.addFocusListener(new ComponentFocusListener());
contentPane.add(jb);
contentPane.add(jc);
jf.setSize(600, 400);
jf.show();

}

static class ComponentFocusListener implements FocusListener
{
public void focusGained(FocusEvent e)
{
//System.out.println("Focus gained in Form");
}

public void focusLost(FocusEvent e)
{
JComponent jc = (JComponent)e.getSource();
System.out.println("LOST :x is"+jc.getBounds().x+" y is :"+jc.getBounds().y);
System.out.println("LOST :Name is"+jc.getName());

}
}

static class ComponentKeyListener implements KeyListener
{
public void keyPressed(KeyEvent event)
{
String key = KeyEvent.getKeyText(event.getKeyCode());
System.out.println("Key :"+ key);
}

public void keyReleased(KeyEvent ke)
{
//System.out.println("Key released in Form");
}

public void keyTyped(KeyEvent ke)
{
//System.out.println("Key typed in Form");
}
}


 
Sajee Joseph
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
add the listeners as given below

Component[] comps = jc.getComponents();
for(int i = 0; i < comps.length; i++)
{
comps[i].addKeyListener(new ComponentKeyListener());
comps[i].addFocusListener(new ComponentFocusListener());
}
for details refer http://www.javaranch.com/ubb/Forum2/HTML/003299.html
 
mohamed zafer
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Joseph...ur solution works...
Mohamed Zafer
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic