JAVA SWT 中禁用的控件的工具提示不可见

Tooltip is not visible for a disabled Control in JAVA SWT

我在 JAVA 应用程序的 GUI 中使用 JAVA SWT。

现在我已经将一个复选框设置为禁用,但我想显示相同的工具提示。

这可能吗?

我的代码是:

myCheckbox.setSelection(false);
myCheckbox.setEnabled(false);
myCheckbox.setToolTipText("Tooltip message");

不,这不可能。

禁用的控件不会生成显示工具提示所需的事件。

正如 greg-449 在他的 中指出的那样,这是不可能的。

但如果您真的想要,可以通过将复选框封装在具有相同工具提示文本的 Composite 中来解决此限制。

此方法由 Andrzej Witecki 在 this Eclipse forum topic 中提出。

一个例子:

public static void main(String[] args) {

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());

    Composite c = new Composite(shell, SWT.NONE);
    c.setLayoutData(new GridData());  // default values so it doesn't grab excess space
    c.setLayout(new FillLayout());

    Button myCheckbox = new Button(c, SWT.CHECK);
    myCheckbox.setText("Checkbox text");
    myCheckbox.setToolTipText("Tooltip message");
    myCheckbox.setEnabled(false);

    // assign the same tooltip to the encapsulating composite
    myCheckbox.getParent().setToolTipText(myCheckbox.getToolTipText());  

    shell.setSize(200, 200);
    shell.open();

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

如果您为禁用的组件(按钮、复选框等)创建一个特定的组合并在该组合上添加工具提示,它将在组件被禁用时显示。

如果您还想在组件启用时显示它,请不要忘记为组件添加工具提示。