Thursday 8 December 2016

SWT: Text listeners

There are two types of text listeners.
a.   ModifyListener
b.   VerifyListener

ModifyListener
ModifyListener is used to get notifications, when the text has been changed. This method is called every time a character is modified. ModifyListener interface provides following methods.
Method
Description
public void modifyText(ModifyEvent e)
Sent when the text is modified.

VerifyListener
Sent when the text is about to be modified.  VerifyListener interface provides following methods.

Method
Description
public void verifyText(VerifyEvent e)
Sent when the text is about to be modified.

package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

 private static int shellWidth = 400;
 private static int shellHeight = 400;

 private static void addWidgetsToShell(Display display, Shell shell) {

  Text text = new Text(shell, SWT.MULTI | SWT.BORDER);
  text.setBounds(10, 10, 300, 100);

  text.addModifyListener(new ModifyListener() {

   @Override
   public void modifyText(ModifyEvent e) {
    System.out.println("Updated Text : " + text.getText());
   }

  });

  text.addVerifyListener(new VerifyListener() {

   @Override
   public void verifyText(VerifyEvent e) {
    System.out.println("Current Text : " + text.getText());
   }

  });

 }

 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);
  shell.setSize(shellWidth, shellHeight);

  addWidgetsToShell(display, shell);

  /* Open shell window */
  shell.open();

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }

  /* Dispose the display */
  display.dispose();
 }
}

Run above application and try to type the string "Hello", you can able to see following messages in console.

Current Text :
Updated Text : H
Current Text : H
Updated Text : He
Current Text : He
Updated Text : Hel
Current Text : Hel
Updated Text : Hell
Current Text : Hell
Updated Text : Hello





Previous                                                 Next                                                 Home

No comments:

Post a Comment