import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class TestText {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
// 创建Label,设定提示信息
Label label = new Label(shell, SWT.WRAP);
label.setText("Input your zip code/n"
+ "Note,only digit or letter is valid!");
// 创建可编辑Text
final Text text = new Text(shell, SWT.BORDER);
// 创建不可编辑Text组件,用于输出提示信息
final Text hintText = new Text(shell, SWT.READ_ONLY);
hintText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// 为text组件加入文本修改事件监听器
text.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
String string = text.getText();
int index = 0;
// 遍历文本内容,检查是否为字母或数字
while (index < string.length()) {
char ch = string.charAt(index);
if (!Character.isLetterOrDigit(ch))
break;
index++;
}
// 若text中输入不合法,则输出错误提示信息
if (index != string.length()) {
hintText.setText("invalid input");
} else {
hintText.setText("");
}
}
});
// 创建Label组件,设定密码提示信息
Label label2 = new Label(shell, SWT.WRAP);
label2.setText("password length no shorter than 6,/n"
+ "and no longer than 8");
// 创建密码Text组件
final Text pwdText = new Text(shell, SWT.BORDER | SWT.PASSWORD);
// 用户输入不得长于8个字符
pwdText.setTextLimit(8);
// 为pwdText组件加入文本修改事件监听器
pwdText.addListener(SWT.Modify, new Listener() {
public void handleEvent(Event event) {
if (pwdText.getText().length() < 6) {
hintText.setText("password not safe");
} else {
hintText.setText("password perfect");
}
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
SWT TEXT基本事件实例
最新推荐文章于 2021-03-20 02:54:06 发布