用于文本控制的SWT / JFace工具提示,当控件中的文本太大而无法显示时

时间:2012-02-01 15:48:45

标签: eclipse swt jface

我知道这可以很容易地实现,但我必须使用标准功能。 我需要在文本字段上显示工具提示,但仅当文本字段中的文本要在字段中显示时才显示。在调整列的大小时,表和树具有此功能,但我没有找到任何类似的文本字段。

我没有在Eclipse中找到这个功能,所以我猜它不是标准功能。 请证明我错了:)。

提前致谢。

1 个答案:

答案 0 :(得分:3)

“标准功能”是什么意思..?将modifyListener添加到Text实例是(imo)标准公平。

这是我的方法

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;


public class TextLabel {
    public TextLabel() {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout());
        shell.setSize(200, 150);
        shell.setText("Long Text content label");

        Text txtLong = new Text(shell, SWT.SINGLE | SWT.BORDER);
        txtLong.addModifyListener(new ModifyListener() {

            @Override
            public void modifyText(ModifyEvent e) {
                Text txtSource = (Text) e.getSource();
                Point size = (new GC(txtSource)).stringExtent(txtSource.getText());
                if(size.x > txtSource.getBounds().width - txtSource.getBorderWidth()) txtSource.setToolTipText(txtSource.getText());
                else txtSource.setToolTipText(null);
            }
        });

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

    public static void main(String args[]) {
        new TextLabel();
    }
}