2013-05-22 81 views
0

我試圖實現一種方法,如果用戶沒有輸入任何內容,則會在文本等控件周圍繪製紅色邊框。我使用eclipse swt。 我的方法看起來像這樣:在錯誤的文字周圍繪製紅色邊框

protected void drawRedBorder(Control cont){ 
    final Control control = cont; 
    cont.getParent().addPaintListener(new PaintListener(){ 
     public void paintControl(PaintEvent e){ 
      GC gc = e.gc; 
      Color red = new Color(null, 255, 0 ,0); 
      gc.setBackground(red); 
      Rectangle rect = control.getBounds(); 
      Rectangle rect1 = new Rectangle(rect.x - 2, rect.y - 2, 
        rect.width + 4, rect.height + 4); 
      gc.setLineStyle(SWT.LINE_SOLID); 
      gc.fillRectangle(rect1); 
     } 
    }); 
} 

它工作正常,當我把它創建帶有文本字段的對話框時。然而,它不起作用,當我在CheckInput()方法中調用它時,它會檢查用戶是否輸入了某個東西。

我試圖通過調用redraw()或update()來解決問題,但沒有任何工作。任何線索我怎麼能解決這個問題?

+0

你嘗試'updateUI()'? – Sam

+0

我可以在哪裏調用此方法? – antumin

+0

調用'drawRedBorder'方法後。 – Sam

回答

0

請嘗試以下操作。

import org.eclipse.swt.*; 
import org.eclipse.swt.events.ModifyEvent; 
import org.eclipse.swt.events.ModifyListener; 
import org.eclipse.swt.events.PaintEvent; 
import org.eclipse.swt.events.PaintListener; 

import org.eclipse.swt.graphics.*; 
import org.eclipse.swt.layout.GridLayout; 
import org.eclipse.swt.widgets.*; 

public class Demo { 

    public static void main (String [] args) { 


     Display display = new Display(); 
     Shell shell = new Shell (display); 
     final Text txt; 
     txt= new Text(shell, SWT.BORDER); 
     drawRedBorder(txt); 

     txt.addModifyListener(new ModifyListener() { 

      @Override 
      public void modifyText(ModifyEvent arg0) { 
       // TODO Auto-generated method stub 
       txt.getParent().redraw(); 

      } 
     }); 


     shell.setLayout(new GridLayout()); 
     shell.open(); 
     while (!shell.isDisposed()) { 
      if (!display.readAndDispatch()) display.sleep(); 
     } 


     display.dispose(); 
    } 

    protected static void drawRedBorder(Control cont){ 
     final Control control = cont; 

     cont.getParent().addPaintListener(new PaintListener(){ 
      public void paintControl(PaintEvent e){ 
       if(((Text) control).getText().length()<=0){ 
        GC gc = e.gc; 
        Color red = new Color(null, 255, 0 ,0); 
        gc.setBackground(red); 
        Rectangle rect = control.getBounds(); 
        Rectangle rect1 = new Rectangle(rect.x - 2, rect.y - 2, 
          rect.width + 4, rect.height + 4); 
        gc.setLineStyle(SWT.LINE_SOLID); 
        gc.fillRectangle(rect1); 
       } 
      } 
     }); 
    } 

} 
相關問題