Use a regular expression to verify input(a phone number is used) : Text Event « SWT « Java Tutorial

Java Tutorial
1. Language
2. Data Type
3. Operators
4. Statement Control
5. Class Definition
6. Development
7. Reflection
8. Regular Expressions
9. Collections
10. Thread
11. File
12. Generics
13. I18N
14. Swing
15. Swing Event
16. 2D Graphics
17. SWT
18. SWT 2D Graphics
19. Network
20. Database
21. Hibernate
22. JPA
23. JSP
24. JSTL
25. Servlet
26. Web Services SOA
27. EJB3
28. Spring
29. PDF
30. Email
31. J2ME
32. J2EE Application
33. XML
34. Design Pattern
35. Log
36. Security
37. Apache Common
38. Ant
39. JUnit
Java
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Tutorial » SWT » Text Event 
17. 18. 4. Use a regular expression to verify input(a phone number is used)
Use a regular expression to verify input(a phone number is used)
/*******************************************************************************
 * Copyright (c) 2000, 2005 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
//package org.eclipse.swt.snippets;
/*
 * Text example snippet: use a regular expression to verify input
 * In this case a phone number is used.
 
 * For a list of all SWT example snippets see
 * http://www.eclipse.org/swt/snippets/
 */
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class TextVerifyInputRegularExpression {
  /*
   * Phone numbers follow the rule
   * [(][1-9][1-9][1-9][)][1-9][1-9][1-9][-][1-9][1-9][1-9][1-9]
   */
  private static final String REGEX = "[(]\\d{3}[)]\\d{3}[-]\\d{4}"//$NON-NLS-1$

  private static final String template = "(###)###-####"//$NON-NLS-1$

  private static final String defaultText = "(000)000-0000"//$NON-NLS-1$

  public static void main(String[] args) {

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    Font font = new Font(display, "Courier New"10, SWT.NONE)//$NON-NLS-1$
    text.setFont(font);
    text.setText(template);
    text.addListener(SWT.Verify, new Listener() {
      // create the pattern for verification
      Pattern pattern = Pattern.compile(REGEX);

      // ignore event when caused by inserting text inside event handler
      boolean ignore;

      public void handleEvent(Event e) {
        if (ignore)
          return;
        e.doit = false;
        if (e.start > 13 || e.end 14)
          return;
        StringBuffer buffer = new StringBuffer(e.text);

        // handle backspace
        if (e.character == '\b') {
          for (int i = e.start; i < e.end; i++) {
            // skip over separators
            switch (i) {
            case 0:
              if (e.start + == e.end) {
                return;
              else {
                buffer.append('(');
              }
              break;
            case 4:
              if (e.start + == e.end) {
                buffer.append(new char[] { '#'')' });
                e.start--;
              else {
                buffer.append(')');
              }
              break;
            case 8:
              if (e.start + == e.end) {
                buffer.append(new char[] { '#''-' });
                e.start--;
              else {
                buffer.append('-');
              }
              break;
            default:
              buffer.append('#');
            }
          }
          text.setSelection(e.start, e.start + buffer.length());
          ignore = true;
          text.insert(buffer.toString());
          ignore = false;
          // move cursor backwards over separators
          if (e.start == || e.start == 9)
            e.start--;
          text.setSelection(e.start, e.start);
          return;
        }

        StringBuffer newText = new StringBuffer(defaultText);
        char[] chars = e.text.toCharArray();
        int index = e.start - 1;
        for (int i = 0; i < e.text.length(); i++) {
          index++;
          switch (index) {
          case 0:
            if (chars[i== '(')
              continue;
            index++;
            break;
          case 4:
            if (chars[i== ')')
              continue;
            index++;
            break;
          case 8:
            if (chars[i== '-')
              continue;
            index++;
            break;
          }
          if (index >= newText.length())
            return;
          newText.setCharAt(index, chars[i]);
        }
        // if text is selected, do not paste beyond range of selection
        if (e.start < e.end && index + != e.end)
          return;
        Matcher matcher = pattern.matcher(newText);
        if (matcher.lookingAt()) {
          text.setSelection(e.start, index + 1);
          ignore = true;
          text.insert(newText.substring(e.start, index + 1));
          ignore = false;
        }
      }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    font.dispose();
    display.dispose();
  }
}
17. 18. Text Event
17. 18. 1. Add focus in/out event to TextAdd focus in/out event to Text
17. 18. 2. Add KeyEvent listener to TextAdd KeyEvent listener to Text
17. 18. 3. Listen to key Traversed eventListen to key Traversed event
17. 18. 4. Use a regular expression to verify input(a phone number is used)Use a regular expression to verify input(a phone number is used)
17. 18. 5. Add events to Text: MouseDown, MouseMove, MouseUp, KeyDown, KeyUp ResizeAdd events to Text: MouseDown, MouseMove, MouseUp, KeyDown, KeyUp Resize
17. 18. 6. Detect when the user scrolls a text controlDetect when the user scrolls a text control
17. 18. 7. Verify input (format for date)Verify input (format for date)
17. 18. 8. Verify input (only allow digits)Verify input (only allow digits)
17. 18. 9. Text TraverseListener: Tab key event (override Tab behavior to traverse out of a Text)Text TraverseListener: Tab key event (override Tab behavior to traverse out of a Text)
17. 18. 10. Text default selection event(Return/Enter key)Text default selection event(Return/Enter key)
17. 18. 11. Add default selection listener to TextAdd default selection listener to Text
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.