Setting component focus in JOptionPane.showOptionDialog()

前端 未结 8 1520
广开言路
广开言路 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:18

    passing null as the last argument is the solution. At least it worked for me.

    String key = null;
    JTextField txtKey = new JTextField();        
    int answerKey = JOptionPane.showOptionDialog(this, new Object[] {pleaseEnterTheKey, txtKey}, decryptionKey, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] {okCaption, cancelCaption}, null);        
    if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
      key = txtKey.getText();
    }
    

    But even this solution bring another problem:

    Focused component and Default component are different. Default component or default button is the button which its onclick fires if you press ENTER KEY.The last argument define the default component which gets the focus too and passing null brings the problem of having no default component! I solved it for my code this way but I guess it is not a best practice:

    String key = null;
        final JTextField txtKey = new JTextField();
        txtKey.addKeyListener(new KeyAdapter() {
    
          @Override
          public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if (keyCode == 10) { //enter key
              Container parent = txtKey.getParent();              
              while (!(parent instanceof JOptionPane)) {
                parent = parent.getParent();
              }
    
              JOptionPane pane = (JOptionPane) parent;
              final JPanel pnlBottom = (JPanel) pane.getComponent(pane.getComponentCount() - 1);
              for (int i = 0; i < pnlBottom.getComponents().length; i++) {
                Component component = pnlBottom.getComponents()[i];
                if (component instanceof JButton) {
                  final JButton okButton = ((JButton)component);
                  if (okButton.getText().equalsIgnoreCase(okCaption)) {
                    ActionListener[] actionListeners = okButton.getActionListeners();
                    if (actionListeners.length > 0) {
                      actionListeners[0].actionPerformed(null);
                    }
                  }
                }
              }
            }
          }
    
        });
    

提交回复
热议问题