Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing Pop-Up Menu of JComboBox from Closing in Java

Tags:

java

swing

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 );
        }
    }
}
like image 593
Ironcache Avatar asked Nov 10 '22 19:11

Ironcache


1 Answers

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.

like image 162
Ironcache Avatar answered Nov 15 '22 12:11

Ironcache