【发布时间】:2015-12-01 13:52:49
【问题描述】:
使用带有自定义组件 (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 还是我需要“直接创建和使用 JOptionPane”?
作为我尝试过的注释(看起来合乎逻辑)
pf.addComponentListener(new ComponentAdapter(){
public void componentShown(ComponentEvent ce){
pf.requestFocus(); //pf.requestFocusInWindow();
}
});
但这也没有运气......
【问题讨论】:
-
另见Dialog Focus ..