Wednesday, November 15, 2006

Are OS-ToolTips not flexible enough / Use JFace ToolTips

How often have you wished that OS-Tooltips would provide more functionalities like MultiLine-Text, Background-Color, Embedded Images, ... . The time you faced those problems is over since today where JFace ToolTips are available to the public.

Usage is fairly straight forward:
Text text = new Text(parent,SWT.BORDER);
text.setText("Hello World");
DefaultToolTip toolTip = new DefaultToolTip(text);
toolTip.setText("Hello World");

Easy isn't it but there are many many more things available to you. You can add any control you want to the tooltip by subclassing org.eclipse.jface.window.ToolTip and providing your own implementation for createToolTipContentArea.
public class MyToolTip extends ToolTip {
private Shell parentShell;

public MyToolTip(Control control) {
this.parentShell = control.getShell();

protected Composite createToolTipContentArea(Event event, Composite parent) {
Composite comp = new Composite(parent,SWT.NONE);
comp.setLayout(new FillLayout());

Button b = new Button(comp,SWT.PUSH);
b.setText("Say Hello");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
MessageBox box = new MessageBox(parentShell,SWT.ICON_INFORMATION);
box.setMessage("Hello World!");
box.setText("Hello World");;

Usage is the same than before:
Text text = new Text(parent,SWT.BORDER);
text.setText("Hello World");

MyToolTip myTooltipLabel = new MyToolTip(text);
myTooltipLabel.setShift(new Point(-5, -5));

The small difference is that you configure the tip to not hide when the user clicks into the ToolTip the ToolTip-Code needs to ensure the hiding by its own by calling hide().

There are other nice feature available to you:

  • possibility to define delay before the ToolTip pops up

  • possibility to define delay how long the ToolTip is shown

  • possibility to define the pop up position

  • possibility to define a shift like shown in the code above

  • possibility to completely control the popup position by overloading ToolTip#getLocation(Point,Event)

  • configure whether the bounds of the display and/or monitors should be:

    • setRespectDisplayBounds(boolean)

    • setRespectMonitorBounds(boolean)

No comments: