2013-05-22 80 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); 
       } 
      } 
     }); 
    } 

} 
相关问题