Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

java - JCombobox focusLost is not firing-why is that?

I have a JCombobox in my code. I have added the FocusLost event. But it didn't fired anyway. I have tried lots of time but didn't find solution.

jcbItemType.addFocusListener(new java.awt.event.FocusAdapter() {
    public void focusLost(java.awt.event.FocusEvent evt) {
        jcbItemTypeFocusLost(evt);
    }
});

private void jcbItemTypeFocusLost(java.awt.event.FocusEvent evt)                                      
    {                                          
        // TODO add your handling code here:
        System.out.println("name=" + ((Component) evt.getSource()).getName());
        System.out.println("index=" + jcbItemType.getSelectedIndex());
    }

But nothing is printed in console. Please suggest me what I am doing wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have found a very simple way to solve this.

The JComboBox default editor has an internal class BasicComboBoxEditor$BorderlessTextField that is the component that gets and loses focus.

It can be accessed simply by

Component component = comboBox.getEditor().getEditorComponent();  
if (component instanceof JTextField) 
    JTextField borderlesstextfield = (JTextField) borderless;

Then add a focus listener like you would to any JTextField

borderlesstextfield.addFocusListener(new FocusListener() 
{
   public void focusGained(FocusEvent e) 
     {
     }
   public void focusLost(FocusEvent e) 
     {
     }
}});

Now you have a FocusListener that will respond as expected to gain and loss of focus for the ComboBox


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...