SWT的Label中 的一个小问题

SWT的Label中 的一个小问题

看下面的代码
Label label  =   new  Label(shell,  SWT.NONE);
Image image 
=   new  Image(display,  "image .gif " );
       
label.setText(
" text " );
label.setImage(image);
label.setText(
" text " );

这个时候label应该显示什么? 我所期待的是文本text. 然而很遗憾的是label还是 显示image. 为什么会这样? 看了SWT的源码我才明白. 下面是Label类里setText方法的一部分,
 1  public   void  setText (String string) {
 2      checkWidget ();
 3       if  (string  ==   null ) error (SWT.ERROR_NULL_ARGUMENT);
 4       if  ((style  &  SWT.SEPARATOR)  !=   0 return ;
 5       /*
 6      * Feature in Windows.  For some reason, SetWindowText() for
 7      * static controls redraws the control, even when the text has
 8      * has not changed.  The fix is to check for this case and do
 9      * nothing.
10       */
11       if  (string.equals (text))  return ;
12      text  =  string;
注意第11行, 当新的string的值和原来的一样时, 方法setText()直接返回了. 按源码里注释的解释,是为了减少Windows下的重画事件以提高性能.

我打算写这个到Eclipse的bug报告里, 我想这应该算一个bug, 欢迎大家讨论.

当然这种情况不是很常见, 但也不是没有, 我就碰到了,  知道了原因后, 解决的方法就很简单了.
label.setText( " text " );
label.setImage(image);
label.setText(label.getText() 
+   " a " );
label.setText(
" text " );
在setText()之前,先用不同的值调用一次setText().

另一个可能更好的方法是, Label类提供一个方法改变显示的模式,比如setShowText(). 但是我没有找到类似的方法.

你可能感兴趣的:(SWT的Label中 的一个小问题)