Thursday 24 November 2016

SWT: Text: Limit the number of characters to be typed

Text class provides setTextLimit method, to limit the number of characters to be typed in text box.

To reset this value to the default, use setTextLimit(Text.LIMIT). Specifying a limit value larger than <code>Text.LIMIT</code> sets the receiver's limit to Text.LIMIT.

Ex:
text1.setTextLimit(10);

Above statement limits number of characters to be typed in text box to 10.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

 private static int xPosition = 30;
 private static int yPosition = 30;
 private static int width = 500;
 private static int height = 30;
 private static int scrollWidth = 500;
 private static int scrollHeight = 350;

 private static int shellWidth = 600;
 private static int shellHeight = 600;

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

  Text text1 = new Text(shell, SWT.BORDER);
  text1.setText("Bordered text box");
  text1.setBounds(xPosition, yPosition, width, height);
  text1.setTextLimit(10);

  yPosition += 40;

  Text text2 = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
  text2.setText("Bordered scrolled text box");
  text2.setBounds(xPosition, yPosition, scrollWidth, scrollHeight);

 }

 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);

  addTextToShell(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();
 }
}


Previous                                                 Next                                                 Home

No comments:

Post a Comment