我正在Java中为SWT和AWT实现一个屏幕键盘.一个重要的事情是将键盘移动到所选文本字段可以显示的位置,而不是位于屏幕键盘后面.
对于AWT,我可以检测当前所选组件的位置
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) { return; } Point ownerLocation = owner.getLocationOnScreen(); Dimension ownerSize = owner.getSize();
如何在SWT中实现相同的逻辑?我通过将一个focuslistener添加到SWT事件队列来获取当前选定的小部件.但是当我打电话时
Point location = new Point(mTextWidget.getLocation().x, mTextWidget.getLocation().y); Dimension dimension = new Dimension(mTextWidget.getSize().x, mTextWidget.getSize().y);
我将获得与父复合相对的位置.
如何才能将特殊小部件的位置与整个屏幕相关联?
我相信Control.toDisplay()方法应该能够将您的坐标转换为相对于屏幕的坐标.
这段代码可以说明您的目标:
package org.eclipse.jface.snippets; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class Bla { public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); final Text t = new Text(shell,SWT.BORDER); t.setBounds(new Rectangle(10,10,200,30)); System.err.println(t.toDisplay(1, 1)); Button b = new Button(shell,SWT.PUSH); b.setText("Show size"); b.setBounds(new Rectangle(220,10,100,20)); b.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { System.err.println(t.toDisplay(1, 1)); } }); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }