【问题标题】:SWT: InputDialog used for password inputSWT: InputDialog 用于密码输入
【发布时间】:2012-10-27 22:17:29
【问题描述】:

如何使用 SWT InputDialog 对象输入密码,用通常的 * 替换普通字符?

还是不可能?

【问题讨论】:

    标签: java dialog swt jface


    【解决方案1】:

    只需创建您自己的Dialog

    public static void main(String[] args) {
        PasswordDialog dialog = new PasswordDialog(new Shell());
        dialog.open();
    
        System.out.println(dialog.getPassword());
    }
    
    public static class PasswordDialog extends Dialog {
        private Text passwordField;
        private String passwordString;
    
        public PasswordDialog(Shell parentShell) {
            super(parentShell);
        }
    
        @Override
        protected void configureShell(Shell newShell)
        {
            super.configureShell(newShell);
            newShell.setText("Please enter password");
        }
    
        @Override
        protected Control createDialogArea(Composite parent) {
            Composite comp = (Composite) super.createDialogArea(parent);
    
            GridLayout layout = (GridLayout) comp.getLayout();
            layout.numColumns = 2;
    
            Label passwordLabel = new Label(comp, SWT.RIGHT);
            passwordLabel.setText("Password: ");
            passwordField = new Text(comp, SWT.SINGLE | SWT.BORDER | SWT.PASSWORD);
    
            GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false);
            passwordField.setLayoutData(data);
    
            return comp;
        }
    
        @Override
        protected void okPressed()
        {
            passwordString = passwordField.getText();
            super.okPressed();
        }
    
        @Override
        protected void cancelPressed()
        {
            passwordField.setText("");
            super.cancelPressed();
        }
    
        public String getPassword()
        {
            return passwordString;
        }
    }
    

    结果如下:

    【讨论】:

    • 这是一个 JFaces 对话框,而不是一个 SWT 对话框。当然相关,但不能完全回答问题。
    • @adamfisk 我不同意。问题是要求InputDialog,这是一个JFace 对话框。这个问题没有提到类似:“我只想要 SWT 对话框,没有 JFace”。
    • 是的——SWT 中不存在 InputDialog,因此 JFaces 肯定是隐含的和必需的——我已更正!
    【解决方案2】:

    您可以继承 InputDialog 并覆盖用于文本控件的样式。

    public class PasswordDialog extends InputDialog {
    
        public PasswordDialog(Shell parentShell, String dialogTitle, String dialogMessage, String initialValue, IInputValidator validator) {
            super(parentShell, dialogTitle, dialogMessage, initialValue, validator);
        }
    
        @Override
        protected int getInputTextStyle() {
            return super.getInputTextStyle() | SWT.PASSWORD;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 2014-02-12
      • 2014-05-11
      • 2011-08-15
      相关资源
      最近更新 更多