2016-06-28 84 views

回答

0

最近,我需要在StyledText中顯示提示。因此我在此分享我的解決方案。

下面顯示的StyledTextMessagesetMessage()方法可用於顯示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); 
    } 

}