Java Tutorial/SWT/Text Event
Содержание
- 1 Add default selection listener to Text
- 2 Add events to Text: MouseDown, MouseMove, MouseUp, KeyDown, KeyUp Resize
- 3 Add focus in/out event to Text
- 4 Add KeyEvent listener to Text
- 5 Detect when the user scrolls a text control
- 6 Listen to key Traversed event
- 7 Text default selection event(Return/Enter key)
- 8 Text TraverseListener: Tab key event (override Tab behavior to traverse out of a Text)
- 9 Use a regular expression to verify input(a phone number is used)
- 10 Verify input (format for date)
- 11 Verify input (only allow digits)
Add default selection listener to Text
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
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 TextSelectionListener {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new RowLayout());
Text text = new Text (shell, SWT.SINGLE | SWT.BORDER);
text.setText ("some text");
text.addListener (SWT.DefaultSelection, new Listener () {
public void handleEvent (Event e) {
System.out.println (e.widget + " - Default Selection");
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Add events to Text: MouseDown, MouseMove, MouseUp, KeyDown, KeyUp Resize
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class TextEventMouseDownMoveUpKey {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Text text = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
for (int i = 0; i < 100; i++) {
text.append(i + "\n");
}
text.setSelection(0);
Listener listener = new Listener() {
int lastIndex = text.getTopIndex();
public void handleEvent(Event e) {
int index = text.getTopIndex();
if (index != lastIndex) {
lastIndex = index;
System.out.println("Scrolled, topIndex=" + index);
}
}
};
/* NOTE: Only detects scrolling by the user */
text.addListener(SWT.MouseDown, listener);
text.addListener(SWT.MouseMove, listener);
text.addListener(SWT.MouseUp, listener);
text.addListener(SWT.KeyDown, listener);
text.addListener(SWT.KeyUp, listener);
text.addListener(SWT.Resize, listener);
shell.pack();
Point size = shell.ruputeSize(SWT.DEFAULT, SWT.DEFAULT);
shell.setSize(size.x - 32, size.y / 2);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Add focus in/out event to Text
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Canvas;
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 FocusEventInOut {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
Text t = new Text(shell, SWT.SINGLE | SWT.BORDER);
t.setBounds(10, 85, 100, 32);
Text t2 = new Text(shell, SWT.SINGLE | SWT.BORDER);
t2.setBounds(10, 25, 100, 32);
t2.addListener(SWT.FocusIn, new Listener() {
public void handleEvent(Event e) {
System.out.println("focus in");
}
});
t2.addListener(SWT.FocusOut, new Listener() {
public void handleEvent(Event e) {
System.out.println("focus out");
}
});
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Add KeyEvent listener to Text
import org.eclipse.swt.SWT;
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 TextKeyEventListener {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
Text t = new Text(shell, SWT.SINGLE | SWT.BORDER);
t.setBounds(10, 85, 100, 32);
Text t2 = new Text(shell, SWT.SINGLE | SWT.BORDER);
t2.setBounds(10, 25, 100, 32);
t2.addListener(SWT.KeyDown, new Listener() {
public void handleEvent(Event e) {
System.out.println("KEY");
}
});
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Detect when the user scrolls a text control
/*******************************************************************************
* 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;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/*
* Detect when the user scrolls a text control
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
public class TextControlUserScroll {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Text text = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
for (int i = 0; i < 32; i++) {
text.append(i + "-This is a line of text in a widget-" + i + "\n");
}
text.setSelection(0);
Listener listener = new Listener() {
int lastIndex = text.getTopIndex();
public void handleEvent(Event e) {
int index = text.getTopIndex();
if (index != lastIndex) {
lastIndex = index;
System.out.println("Scrolled, topIndex=" + index);
}
}
};
/* NOTE: Only detects scrolling by the user */
text.addListener(SWT.MouseDown, listener);
text.addListener(SWT.MouseMove, listener);
text.addListener(SWT.MouseUp, listener);
text.addListener(SWT.KeyDown, listener);
text.addListener(SWT.KeyUp, listener);
text.addListener(SWT.Resize, listener);
ScrollBar hBar = text.getHorizontalBar();
if (hBar != null) {
hBar.addListener(SWT.Selection, listener);
}
ScrollBar vBar = text.getVerticalBar();
if (vBar != null) {
vBar.addListener(SWT.Selection, listener);
}
shell.pack();
Point size = shell.ruputeSize(SWT.DEFAULT, SWT.DEFAULT);
shell.setSize(size.x - 32, size.y / 2);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Listen to key Traversed event
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class TraverseEventListen {
public static void main(String[] args) {
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Text text = new Text(shell, SWT.SINGLE | SWT.BORDER);
text.setText("press tab to draw");
text.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
e.doit = true;
GC gc = new GC(text);
// Erase background first.
Rectangle rect = text.getClientArea();
gc.fillRectangle(rect.x, rect.y, rect.width, rect.height);
Font font = new Font(display, "Arial", 32, SWT.BOLD);
gc.setFont(font);
gc.drawString("tab event", 15, 10);
gc.dispose();
}
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
Text default selection event(Return/Enter key)
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.rubo;
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 TextDefaultSelection {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new RowLayout());
Combo combo = new Combo(shell, SWT.NONE);
combo.setItems(new String[] { "A-1", "B-1", "C-1" });
Text text = new Text(shell, SWT.SINGLE | SWT.BORDER);
text.setText("some text");
combo.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
System.out.println(e.widget + " - Default Selection");
}
});
text.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
System.out.println(e.widget + " - Default Selection");
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Text TraverseListener: Tab key event (override Tab behavior to traverse out of a Text)
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class TextTraverseListenerTab {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setBounds(10, 10, 200, 200);
Text text1 = new Text(shell, SWT.MULTI | SWT.WRAP);
text1.setBounds(10, 10, 150, 50);
text1.setText("Tab will traverse out from here.");
text1.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
e.doit = true;
}
}
});
Text text2 = new Text(shell, SWT.MULTI | SWT.WRAP);
text2.setBounds(10, 100, 150, 50);
text2.setText("But Tab will NOT traverse out from here (Ctrl+Tab will).");
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
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.rupile(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 + 1 == e.end) {
return;
} else {
buffer.append("(");
}
break;
case 4:
if (e.start + 1 == e.end) {
buffer.append(new char[] { "#", ")" });
e.start--;
} else {
buffer.append(")");
}
break;
case 8:
if (e.start + 1 == 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 == 5 || 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 + 1 != 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();
}
}
Verify input (format for date)
/*******************************************************************************
* 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: verify input (format for date)
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import java.util.Calendar;
import org.eclipse.swt.SWT;
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 TextVerifyInputFormatDate {
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);
text.setText("YYYY/MM/DD");
;
final Calendar calendar = Calendar.getInstance();
text.addListener(SWT.Verify, new Listener() {
boolean ignore;
public void handleEvent(Event e) {
if (ignore)
return;
e.doit = false;
StringBuffer buffer = new StringBuffer(e.text);
char[] chars = new char[buffer.length()];
buffer.getChars(0, chars.length, chars, 0);
if (e.character == "\b") {
for (int i = e.start; i < e.end; i++) {
switch (i) {
case 0: /* [Y]YYY */
case 1: /* Y[Y]YY */
case 2: /* YY[Y]Y */
case 3: /* YYY[Y] */{
buffer.append("Y");
break;
}
case 5: /* [M]M */
case 6: /* M[M] */{
buffer.append("M");
break;
}
case 8: /* [D]D */
case 9: /* D[D] */{
buffer.append("D");
break;
}
case 4: /* YYYY[/]MM */
case 7: /* MM[/]DD */{
buffer.append("/");
break;
}
default:
return;
}
}
text.setSelection(e.start, e.start + buffer.length());
ignore = true;
text.insert(buffer.toString());
ignore = false;
text.setSelection(e.start, e.start);
return;
}
int start = e.start;
if (start > 9)
return;
int index = 0;
for (int i = 0; i < chars.length; i++) {
if (start + index == 4 || start + index == 7) {
if (chars[i] == "/") {
index++;
continue;
}
buffer.insert(index++, "/");
}
if (chars[i] < "0" || "9" < chars[i])
return;
if (start + index == 5 && "1" < chars[i])
return; /* [M]M */
if (start + index == 8 && "3" < chars[i])
return; /* [D]D */
index++;
}
String newText = buffer.toString();
int length = newText.length();
StringBuffer date = new StringBuffer(text.getText());
date.replace(e.start, e.start + length, newText);
calendar.set(Calendar.YEAR, 1901);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DATE, 1);
String yyyy = date.substring(0, 4);
if (yyyy.indexOf("Y") == -1) {
int year = Integer.parseInt(yyyy);
calendar.set(Calendar.YEAR, year);
}
String mm = date.substring(5, 7);
if (mm.indexOf("M") == -1) {
int month = Integer.parseInt(mm) - 1;
int maxMonth = calendar.getActualMaximum(Calendar.MONTH);
if (0 > month || month > maxMonth)
return;
calendar.set(Calendar.MONTH, month);
}
String dd = date.substring(8, 10);
if (dd.indexOf("D") == -1) {
int day = Integer.parseInt(dd);
int maxDay = calendar.getActualMaximum(Calendar.DATE);
if (1 > day || day > maxDay)
return;
calendar.set(Calendar.DATE, day);
} else {
if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) {
char firstChar = date.charAt(8);
if (firstChar != "D" && "2" < firstChar)
return;
}
}
text.setSelection(e.start, e.start + length);
ignore = true;
text.insert(newText);
ignore = false;
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Verify input (only allow digits)
/*******************************************************************************
* Copyright (c) 2000, 2004 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: verify input (only allow digits)
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.swt.SWT;
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 TextVerifyInputDigits {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
Text text = new Text(shell, SWT.BORDER | SWT.V_SCROLL);
text.setBounds(10, 10, 200, 200);
text.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String string = e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
for (int i = 0; i < chars.length; i++) {
if (!("0" <= chars[i] && chars[i] <= "9")) {
e.doit = false;
return;
}
}
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}