Question

I can't figure out how to implement a focus listener on a comboxbox. I understand that it is not a simple thing to do, yet other people seem to have gotten it to work[1][2][3], yet I am unable to duplicate their results after carefully examining each one. After extensive searching all over the web, checking the latest Oracle guide, Oracle documentation, etc., I've come here. My question is simply:

Is it possible to add focus listeners to comboboxes and if so how?

The goal is to create a field basically identical to Google search. You can type in a search query, and it will populate a dropdown below the text field with possible search matches. If all else fails I'll just have both a comboxbox and a textfield on top of each other and setup some sort of elaborate visibility toggling, but I would prefer not to...

Using:
Java 1.7.0_21 (← side note: why do I have to escape this underscore to italicize this text? What does underscore do?)
Windows 7 x64

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

public class focustest extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    public focustest theframe;
    
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                focustest theframe = new focustest();
                theframe.setVisible(true);
            }
        });
    }

    public focustest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 106);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
        JComboBox comboBox = new JComboBox();
        comboBox.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent arg0) {
                JOptionPane.showMessageDialog(theframe, "focus gained!", null,JOptionPane.PLAIN_MESSAGE);
            }
            @Override
            public void focusLost(FocusEvent arg0) {
                JOptionPane.showMessageDialog(theframe, "focus lost!", null,JOptionPane.PLAIN_MESSAGE);
            }
        });
        comboBox.setEditable(true);
        contentPane.add(comboBox, BorderLayout.NORTH);
        textField = new JTextField();
        contentPane.add(textField, BorderLayout.SOUTH);
        textField.setColumns(10);
    }
    
}
Était-ce utile?

La solution

comboBox.getEditor().getEditorComponent().addFocusListener(new FocusAdapter() {
   // ....
}

and good luck with that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top