3

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.

payal_suthar
  • 355
  • 8
  • 31
  • fyi: if bounty is not provided, I will only get half of it. The rest will be lost. Of course I can accept that my answer might not be helpful enough. – Marinos An Mar 15 '18 at 09:48

1 Answers1

2

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) {}
    });
Marinos An
  • 9,481
  • 6
  • 63
  • 96
  • I don't find your answer anywhere relevant to my question.My issue is that focus lost event is not working on combo box even if tab is pressed or mouse is clicked. Note: there are many other elements on the panel but the focus lost event works on all of them but combo box. – payal_suthar Apr 09 '18 at 10:18