Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 992
payal_suthar Avatar asked Nov 18 '25 08:11

payal_suthar


1 Answers

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) {}
    });
like image 90
Marinos An Avatar answered Nov 21 '25 09:11

Marinos An



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!