我正在用 Java 为 SWT 和 AWT 实现一个屏幕键盘。 一件重要的事情是将键盘移动到所选文本字段可以显示的位置,而不是位于屏幕键盘后面。
对于 AWT,我可以检测当前选定组件的位置
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (owner == null) {
return;
}
Point ownerLocation = owner.getLocationOnScreen();
Dimension ownerSize = owner.getSize();
如何在 SWT 中实现相同的逻辑? 我通过向 SWT 事件队列添加焦点监听器来获取当前选定的小部件。但是当我调用
Point location = new Point(mTextWidget.getLocation().x, mTextWidget.getLocation().y);
Dimension dimension = new Dimension(mTextWidget.getSize().x, mTextWidget.getSize().y);
我将获得相对于父组合的位置。
如何获取特定小部件相对于整个屏幕的位置?
最佳答案
我相信方法Control.toDisplay()应该能够将您的坐标转换为相对于屏幕的坐标。
这snippet可以说明你在追求什么:
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();
}
}
关于java - 在屏幕上查找复合位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/339821/