SWT实现Text输入自动提示

吕宣
2023-12-01

	/**
	 * 生成自动提示
	 * 
	 * @param textObj
	 *            要自动提示的文本控件
	 */
	private void createAutoTip(Text textObj, String[] proposals) {

		textContentAdapter = new TextContentAdapter() {

			/**
			 * 在控件中添加该关键字
			 * 
			 * @param control
			 * @param text
			 * @param cursorPosition
			 */
			@Override
			public void insertControlContents(Control control, String text, int cursorPosition) {
				Point selection = ((Text) control).getSelection();
				((Text) control).insert(text);
				if (cursorPosition < text.length()) {
					((Text) control).setSelection(selection.x + cursorPosition, selection.x + cursorPosition);
				}
			}

			/**
			 * 设置关键字
			 * 
			 * @param control
			 * @param text
			 * @param cursorPosition
			 */
			@Override
			public void setControlContents(Control control, String text, int cursorPosition) {
				int len = textObj.getText().lastIndexOf(" ");
				String temp = textObj.getText();
				if (len == -1) {
					super.setControlContents(control, text, cursorPosition);
				} else {
					temp = temp.substring(0, temp.lastIndexOf(" "));
					temp = temp.concat(" ").concat(text);
					super.setControlContents(control, temp, cursorPosition);
				}

			}

			/**
			 * 处理搜索关键字
			 * 
			 * @param control
			 * @return
			 */
			@Override
			public String getControlContents(Control control) {
				String temp = ((Text) control).getText();
				temp = temp.substring(temp.lastIndexOf(" ") + 1);
				return temp;
			}

			public Point getSelection(Control control) {
				return super.getSelection(textObj);
			}

			@Override
			public Rectangle getInsertionBounds(Control control) {
				return super.getInsertionBounds(control);
			}

			@Override
			public void setSelection(Control control, Point range) {
				super.setSelection(control, range);
			}
		};

		autoCompleteField = new AutoCompleteField(textObj, textContentAdapter, proposals);
	}
 类似资料: