如何在JOptionPane.showConfirmDialog中请求聚焦组件?

时间:2015-12-01 13:52:49

标签: java swing focus

JOptionPane.showConfirmDialog与自定义组件JPanel一起使用,我希望在打开时专注于特定组件(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或者我需要&#34;直接创建和使用JOptionPane&#34;?

作为我试过的一个注释(似乎是合乎逻辑的)

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

但这也没有运气......

2 个答案:

答案 0 :(得分:4)

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

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);
            }
        });
    }
});

答案 1 :(得分:2)

您对自己的答案非常接近解决方案。虽然添加/删除是混乱的,但你是对的。这有点整洁。

试试这个:

JOptionPane.showConfirmDialog()

请确保在致电{{1}}

之前填写该代码

如果您需要更多信息Setting component focus in JOptionPane.showOptionDialog()

,我在此处找到了答案