将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);
}
}
Run Code Online (Sandbox Code Playgroud)
是否有可能以某种方式请求关注我想要的内容JPasswordField pf还是我需要“直接创建和使用 JOptionPane”?
作为我尝试过的笔记(似乎合乎逻辑)
pf.addComponentListener(new ComponentAdapter(){
public void componentShown(ComponentEvent ce){
pf.requestFocus(); //pf.requestFocusInWindow();
}
});
Run Code Online (Sandbox Code Playgroud)
但也没有运气...
我通过添加和删除侦听器找到了一种方法,但我不太喜欢它。我愿意接受更好的解决方案。
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);
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1039 次 |
| 最近记录: |