【问题标题】:Get Cursor Control for Disabled Control获取禁用控件的光标控件
【发布时间】:2020-05-05 08:02:29
【问题描述】:

我想要控制鼠标悬停在上面,这通常由Display#getCursorControl 完成。但是,当层次结构中的一个控件被禁用时,此方法不再起作用:

示例:

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setSize(400, 300);
    shell.setLayout(new GridLayout(2, false));

    final Label mouseControl = new Label(shell, SWT.BORDER);
    mouseControl.setLayoutData(GridDataFactory.fillDefaults().span(2, 1).grab(true, true).create());
    display.addFilter(SWT.MouseMove,
            e -> mouseControl.setText("" + e.display.getCursorControl()));

    final Group enabledGroup = new Group(shell, SWT.NONE);
    enabledGroup.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create());
    enabledGroup.setText("Enabled Group");
    createControls(enabledGroup);

    final Group disabledGroup = new Group(shell, SWT.NONE);
    disabledGroup.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create());
    disabledGroup.setText("Disabled Group");
    disabledGroup.setEnabled(false);
    createControls(disabledGroup);

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

private static void createControls(Composite parent) {
    parent.setLayout(new GridLayout());

    final Label label = new Label(parent, SWT.NONE);
    label.setText("Label");

    final Text text = new Text(parent, SWT.BORDER);
    text.setText("Text");
}

将鼠标悬停在左侧标签上,然后在右侧标签上。该控件仅对启用的父级显示,否则显示外壳。

如何获得鼠标指针下方的控件?我必须自己实现这个功能吗?有什么方法可以帮助我还是我必须计算树内每个控件的边界并检查它是否在鼠标位置上?

【问题讨论】:

    标签: java swt


    【解决方案1】:

    我在Display 中看不到任何有用的东西。

    以下内容将在 Shell 的子项中搜索包含光标的控件并与禁用的控件一起使用:

    static Control findCursorinShellChildren(final Shell shell)
    {
      return findLocationInCompositeChildren(shell, shell.getDisplay().getCursorLocation());
    }
    
    
    static Control findLocationInCompositeChildren(final Composite composite, final Point displayLoc)
    {
      final var compositeRelativeLoc = composite.toControl(displayLoc);
    
      for (final var child : composite.getChildren())
       {
         if (child.getBounds().contains(compositeRelativeLoc))
          {
            if (child instanceof Composite)
             {
               final var containedControl = findLocationInCompositeChildren((Composite)child, displayLoc);
               return containedControl != null ? containedControl : child;
             }
    
            return child;
          }
       }
    
      return null;
    }
    

    我想这会比Display.getCursorControl慢很多

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多