Search code examples
swt

How to set the initial message for SWT Combo


SWT Text has a method called setMessage which can be used with SWT.SEARCH to put an initial faded-out message in the text box.

Can something similar be done with SWT Combo? It seems it does not have the setMessage() method, so it seems like some other trick needs to be applied here.


Solution

  • You are right, the Combo does not have regular API to set a message like the text widget does.

    You could try to use a PaintListener to draw the message text while the Combo text is empty.

    combo.addPaintListener( new PaintListener() {
      @Override
      public void paintControl( PaintEvent event ) {
        if( combo.getText().isEmpty() ) {
          int x = ...; // indent some pixels
          int y = ...; // center vertically
          event.gc.drawText( "enter something", x, y );
        }
      }
    } );
    

    In addition, you would need several listeners that redraw the Combo after its native appearance was updated.

    combo.addListener( SWT.Modify, event -> combo.redraw() );
    

    A modify listener is certainly required to show/hide the message but there are probably more listeners necessary to redraw the message when it is invalidated. This answer may give further hints which events are necessary to capture: How to display a hint message in an SWT StyledText

    Note, however, that drawing onto controls other than Canvas is unsupported and may not work on all platforms.