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

标签 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 或者我是否需要“直接创建和使用 JOptionPane”?

作为一个注释,我已经尝试过(看起来合乎逻辑的)

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

关于java - 如何在 JOptionPane.showConfirmDialog 的组件上请求焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34022134/

相关文章:

javascript - 类型错误 : Cannot read property 'focus' of undefined in ReactJS

java - 创建 Hibernate 类型以使用 PostgreSQL 保存 JSONObject

java - 如何解析具有相同名称但不同级别的标签的 XML?

java - 如何在 Java 中创建停靠面板?

ios - tvOS 如何检查 UITabBar 是否聚焦

macos - SwiftUI:从 macOS TextField 中删除 'Focus Ring' 高亮边框

java - Android 动态微调器更新

java - 需要一个视觉上令人愉悦的 UML 图工具

java - 如何让我的按钮切换而不循环?

swing - 在 IntelliJ 的停靠面板中显示时,Graphstream 渲染偶尔会消失