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() 来解决问题,但没有任何效果。任何线索我可以如何解决这个问题?

4

1 回答 1

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);
               }
            }
        });
    }

} 
于 2013-05-31T09:28:41.427 回答