gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:05:48 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com