payal_suthar
payal_suthar

Reputation: 455

Focuslost event on Jcombobox in netbeans

I am trying to have a bind a focuslost event on my combobox but it's not happening.

Here is my code-:

jComboBox1.addFocusListener(new FocusListener(){
        public void focusGained(FocusEvent e){

        }
        public void focusLost(FocusEvent e){
         JOptionPane.showConfirmDialog(null,"focuslost");
          }
      });

I also tried this-:

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;

But i am getting error on this line-

 JTextField borderlesstextfield = (JTextField) borderless;

I am new to netbeans. Kindly guide me.Thank you in advance.

Upvotes: 3

Views: 186

Answers (1)

Marinos An
Marinos An

Reputation: 10826

I tested this(Adding the JComboBox inside a JPanel ). If there are more elements inside the panel the focuslost is triggered when pressing tab or clicking on another element.

Considering that you do not have any other elements or you want the focus lost event to trigger also when you click somewhere on the window:

Keep your focus listener as is and add the following after the auto-generated initComponents():

    jPanel1.setFocusable(true);
    jPanel1.setRequestFocusEnabled(true);
    jPanel1.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {}

        @Override
        public void mousePressed(MouseEvent e) {
            jPanel1.requestFocusInWindow();
        }

        @Override
        public void mouseReleased(MouseEvent e) {}

        @Override
        public void mouseEntered(MouseEvent e) {}

        @Override
        public void mouseExited(MouseEvent e) {}
    });

Upvotes: 2

Related Questions