9

我正在用 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);

我将获得相对于父复合材料的位置。

我怎样才能得到一个特殊的小部件相对于整个屏幕的位置?

4

1 回答 1

17

我相信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();
    }
}
于 2008-12-04T08:04:05.113 回答