Setting component focus in JOptionPane.showOptionDialog()

前端 未结 8 1478
广开言路
广开言路 2020-12-10 13:59

In order to have custom button captions in an input dialog, I created the following code:

String key = null;
JTextField txtKey = new JTextField();        
in         


        
相关标签:
8条回答
  • 2020-12-10 14:23

    The trick is to (a) use an AncestorListener on the text component to request focus, and when the focus is lost again (given to the default button), ask for focus a second time using a FocusListener on the text component (but don't keep asking for focus after that):

    final JPasswordField accessPassword = new JPasswordField();
    
    accessPassword.addAncestorListener( new AncestorListener()
    {
      @Override
      public void ancestorRemoved( final AncestorEvent event )
      {
      }
      @Override
      public void ancestorMoved( final AncestorEvent event )
      {
      }
      @Override
      public void ancestorAdded( final AncestorEvent event )
      {
        // Ask for focus (we'll lose it again)
        accessPassword.requestFocusInWindow();
      }
    } );
    
    accessPassword.addFocusListener( new FocusListener()
    {
      @Override
      public void focusGained( final FocusEvent e )
      {
      }
      @Override
      public void focusLost( final FocusEvent e )
      {
        if( isFirstTime )
        {
          // When we lose focus, ask for it back but only once
          accessPassword.requestFocusInWindow();
          isFirstTime = false;
        }
      }
      private boolean isFirstTime = true;
    } );
    
    0 讨论(0)
  • 2020-12-10 14:26

    Dialog Focus shows how you can easily set the focus on any component in a modal dialog.

    0 讨论(0)
提交回复
热议问题