File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes JComboBox and FocusListener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JComboBox and FocusListener" Watch "JComboBox and FocusListener" New topic
Author

JComboBox and FocusListener

mohamed zafer
Ranch Hand

Joined: Nov 03, 2000
Posts: 62
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

Joined: Jan 17, 2001
Posts: 200
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

Joined: Nov 03, 2000
Posts: 62
Thanks Joseph...ur solution works...
Mohamed Zafer
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JComboBox and FocusListener