java – 如何在JOptionPane.showConfirmDialog中的组件上requestFocus?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 如何在JOptionPane.showConfirmDialog中的组件上requestFocus?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2179字,纯文字阅读大概需要4分钟。
内容图文
使用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中的组件上requestFocus?全部内容,希望文章能够帮你解决java – 如何在JOptionPane.showConfirmDialog中的组件上requestFocus?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。