如何在SWT StyledText中显示提示消息

时间:2016-06-28 10:18:31

标签: eclipse swt

SWT Text有一个名为setMessage()的方法,可用于将消息显示为用户的提示,指明该字段的用途。

似乎StyledText没有setMessage()方法。尽管如此,可以使用StyledText做类似的事情吗?

1 个答案:

答案 0 :(得分:0)

最近,我需要在StyledText中显示提示。因此我在这里分享我的解决方案

下面显示的setMessage() StyledTextMessage方法可用于在StyledText窗口小部件上显示提示。该类添加了一个绘制侦听器来绘制消息文本和几个侦听器并显示过滤器,以便在消息无效时重绘该消息。

public class StyledTextMessage {

  public static void main( String[] args ) {
    Display display = new Display();
    Shell shell = new Shell( display );
    shell.setLayout( new FillLayout() );
    StyledText styledText2 = new StyledText( shell, SWT.BORDER );
    Button button = new Button( shell, SWT.PUSH );
    button.setText( "Push Button" );
    new StyledTextMessage( styledText2 ).setMessage( "Please enter something stylish..." );
    shell.setSize( 600, 600 );
    shell.open();
    while( !shell.isDisposed() ) {
      if( !display.readAndDispatch() )
        display.sleep();
    }
    display.dispose();
  }

  private static final int MARGIN = 2;
  private static int[] INVALIDATE_EVENTS = { SWT.Activate, SWT.Deactivate, SWT.Show, SWT.Hide };

  private final StyledText styledText;
  private final Listener invalidateListener;
  private final Color textColor;
  private String message;
  private int verticalOffsetLines;

  public StyledTextMessage( StyledText styledText ) {
    this.styledText = Objects.requireNonNull( styledText );
    this.invalidateListener = this::handleInvalidatedEvent;
    this.textColor = getTextColor();
    this.message = "";
    initialize();
  }

  public void setMessage( String message ) {
    this.message = Objects.requireNonNull( message );
    this.styledText.redraw();
  }

  public boolean isMessageShowing() {
    return !message.isEmpty() && styledText.getContent().getCharCount() == 0;
  }

  private void initialize() {
    styledText.addListener( SWT.Paint, this::handlePaintEvent );
    styledText.addListener( SWT.Resize, event -> styledText.redraw() );
    styledText.addListener( SWT.Dispose, this::handleDispose );
    for( int eventType : INVALIDATE_EVENTS ) {
      styledText.getDisplay().addFilter( eventType, invalidateListener );
    }
  }

  private Color getTextColor() {
    return styledText.getDisplay().getSystemColor( SWT.COLOR_GRAY );
  }

  private void handlePaintEvent( Event event ) {
    if( isMessageShowing() ) {
      drawHint( event.gc, event.x, event.y );
    }
  }

  private void handleDispose( Event event ) {
    for( int eventType : INVALIDATE_EVENTS ) {
      styledText.getDisplay().removeFilter( eventType, invalidateListener );
    }
  }

  private void handleInvalidatedEvent( Event event ) {
    styledText.redraw();
  }

  private void drawHint( GC gc, int x, int y ) {
    int verticalOffset = verticalOffsetLines * gc.getFontMetrics().getHeight();
    gc.setForeground( textColor );
    gc.drawText( message, x + MARGIN, y + MARGIN - verticalOffset, SWT.DRAW_DELIMITER | SWT.DRAW_TRANSPARENT );
  }

}