o7planning

Java SWT Password Field Tutorial with Examples

  1. SWT PasswordField
  2. PasswordField example

1. SWT PasswordField

Password Field is a user control allowing users to enter their password, its contents can be read by application. Password Field does not display the characters that users enter, instead of that, it displays a circle corresponding to each character typed.
In order to create a password field, you need to create it from Text class with style SWT.PASSWORD. Note that the password field is entered in single line and not in multiple lines.
// Create a Password field.
Text passwordField = new Text(shell, SWT.SINGLE | SWT.BORDER | SWT.PASSWORD);


// Set echo char.
passwordField.passwordField.setEchoChar('*');

2. PasswordField example

PasswordFieldDemo.java
package org.o7planning.swt.passwordfield;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class PasswordFieldDemo {

   public static void main(String[] args) {

       Display display = new Display();
       Shell shell = new Shell(display);

       // Layout
       RowLayout rowLayout = new RowLayout();
       rowLayout.spacing = 10;
       rowLayout.marginLeft = 10;
       rowLayout.marginTop = 10;
       shell.setLayout(rowLayout);

       Text passwordField = new Text(shell, SWT.SINGLE | SWT.BORDER  | SWT.PASSWORD);
       passwordField.setEchoChar('*');

       Button button = new Button(shell, SWT.PUSH);
       button.setText("Show Password");

       Label labelInfo = new Label(shell, SWT.NONE);
       labelInfo.setText("?");

       button.addSelectionListener(new SelectionAdapter() {

           @Override
           public void widgetSelected(SelectionEvent e) {
               labelInfo.setText(passwordField.getText());
               labelInfo.pack();
           }
       });

       shell.setText("SWT Password Field (o7planning.org)");
       shell.setSize(400, 200);
       shell.open();
       while (!shell.isDisposed()) {
           if (!display.readAndDispatch())
               display.sleep();
       }
       display.dispose();
   }

}