Ironcache
Ironcache

Reputation: 1759

Preventing Pop-Up Menu of JComboBox from Closing in Java

I'm looking to prevent a pop-up window from closing in response to focus transfer.

A code example is attached. My goal is to be able to expand the combo box drop-down menu, and then select the text field WITHOUT having the drop-down menu disappear. Is this possible?

import java.awt.BorderLayout;

import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JTextField;

public class ComboBoxPopupTest
{
    public static void main( String[] args )
    {
        new ComboBoxPopupTest();
    }

    public ComboBoxPopupTest()
    {
        MyDialog dialog = new MyDialog();
        dialog.setVisible( true );
        MyComboBoxDialog window = new MyComboBoxDialog();
        window.setVisible( true );
    }


    private class MyDialog extends JDialog
    {
        public MyDialog()
        {
            setLayout( new BorderLayout() );
            JTextField textField = new JTextField("Text Field");
            textField.putClientProperty( "doNotCancelPopup", Boolean.TRUE );  // FIXME: I Don't prevent the pop-up from closing!
            add( textField, BorderLayout.CENTER );
            setSize( 400, 400 );
        }
    }

    private class MyComboBoxDialog extends JDialog
    {
        public MyComboBoxDialog()
        {
            setLayout( new BorderLayout() );
            add( new JComboBox( new String[]{"String1", "String2", "String3"} ), BorderLayout.CENTER );
            setSize( 400, 400 );
        }
    }
}

Upvotes: 5

Views: 688

Answers (1)

Ironcache
Ironcache

Reputation: 1759

My hack solution in the end was to make the other container completely non-focusable. This is not acceptable as a general solution, but I'll accept it as the answer unless someone has something better.

Upvotes: 1

Related Questions