这可能看起来微不足道,但我无法弄清楚如何在此对话框焦点中给出密码框.
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
public class PasswordBox {
@SuppressWarnings("unused")
public String prompt() {
JPasswordField pass = new JPasswordField(10);
int action = JOptionPane.showConfirmDialog(null, pass,"Enter Password",JOptionPane.OK_CANCEL_OPTION);
return new String(pass.getPassword());
}
}
Run Code Online (Sandbox Code Playgroud)
我从其他类调用它: String tmpPASS = new PasswordBox().prompt();
出于某种原因,当对话框出现时,"确定"按钮会获得焦点.
stacktrace(参见Eng.Fouad的回答):
at javax.swing.JComponent.addNotify(Unknown Source)
at PasswordBox$1.addNotify(PasswordBox.java:14)
at java.awt.Container.addNotify(Unknown Source)
Run Code Online (Sandbox Code Playgroud) 将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, …Run Code Online (Sandbox Code Playgroud)