如何在 JOptionPane.showConfirmDialog 中的组件上请求焦点?

How can I requestFocus on component in JOptionPane.showConfirmDialog?

使用带有自定义组件 (JPanel) 的 JOptionPane.showConfirmDialog,我喜欢在打开时专注于特定组件 (JPasswordField)。如何实现?

代码示例: 当对话框打开时 JPasswordField pf 应该有焦点...

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;


public class JTestOptionDialog {

  public static void main(String[] args) {  
    JFrame frame = new JFrame("Test showConfirmDialog");
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(new JPanel());
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    JLabel label = new JLabel("<html><body>To access insert <b>password</b></body></html>");
    JPasswordField pf = new JPasswordField();
    JPanel panel = new JPanel(new GridBagLayout());
    panel.add(label,new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
    panel.add(pf,new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
    pf.requestFocus(); //THIS IS WHAT I LIKE TO HAVE FOCOUS WHEN DIALOG OPENS
    int retVal = JOptionPane.showConfirmDialog(frame,panel,"Impostazioni",JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
    System.out.println(retVal);
  }
}

是否可以通过某种方式请求关注我想要的 JPasswordField pf 或者我是否需要 "To create and use an JOptionPane directly"?

作为我尝试过的注释(看起来合乎逻辑)

pf.addComponentListener(new ComponentAdapter(){
  public void componentShown(ComponentEvent ce){
    pf.requestFocus(); //pf.requestFocusInWindow();
  }
});

但也没有运气...

我通过添加和删除侦听器找到了一种方法,但我不太喜欢它。我愿意接受更好的解决方案。

pf.addAncestorListener(new AncestorListener() {     

    public void ancestorRemoved(AncestorEvent event) {}

    public void ancestorMoved(AncestorEvent event) {}            

    public void ancestorAdded(final AncestorEvent event) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                event.getComponent().requestFocusInWindow();
                event.getComponent().removeAncestorListener(this);
            }
        });
    }
});

您已经非常接近您自己的答案了。虽然 adding/removing 很乱,但你是对的。这样比较整洁。

试试这个:

pf.addAncestorListener(new AncestorListener() {
    @Override
    public void ancestorRemoved(AncestorEvent event) {}

    @Override
    public void ancestorMoved(AncestorEvent event) {}

    @Override
    public void ancestorAdded(AncestorEvent event) {
        event.getComponent().requestFocusInWindow();
    }
});

并确保在调用 JOptionPane.showConfirmDialog()

之前输入该代码

如果您想了解更多信息,我在这里找到了答案Setting component focus in JOptionPane.showOptionDialog()