在SWT标签中以粗体显示部分文本,在斜体中显示部分部分

时间:2015-03-05 09:43:01

标签: java swt jface

我必须向用户显示一些警告信息,如

"如果您还原数据,更新的更改将丢失,因此重新检查一次"

在德语中我也要使用粗体和斜体字符串。

在两种语言中,对话框的高度和宽度应相同

public class BoldTextMessageDialog extends ZedisTrayDialog {

  private Composite container;
  private String firstSring;
  private String secondString;
  private String boldString;
  private Button restoreButton;
  private Button cancelButton;

  public BoldTextMessageDialog(Shell shell, String firstSring, String   secondString, String boldString) {
    super(shell);
    this.firstSring = firstSring;
    this.secondString = secondString;
    this.boldString = boldString;
  }

  @Override
  protected Control createDialogArea(Composite parent) {

    container = new Composite(parent, SWT.NONE);
    container.setLayout(new FormLayout());
    GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);

    gd.heightHint = 300;
    gd.widthHint = 500;
    container.setLayoutData(gd);

    Label warningLabel = new Label(container, SWT.NONE);
    warningLabel.setImage(parent.getDisplay().getSystemImage(SWT.ICON_WARNING));

    FormData fd = new FormData();
    fd.left = new FormAttachment(0, 5);
    fd.top = new FormAttachment(0, 5);
    warningLabel.setLayoutData(fd);

    Label firstLabel = new Label(container, SWT.WRAP);
    firstLabel.setText(firstSring);

    fd = new FormData();
    fd.left = new FormAttachment(warningLabel, 10);
    fd.right = new FormAttachment(100, 0);
    fd.top = new FormAttachment(0, 10);
    firstLabel.setLayoutData(fd);

    Label secLabel = new Label(container, SWT.WRAP);
    secLabel.setText(boldString);
    secLabel.setFont(FontCache.getBoldFont());

    fd = new FormData();
    fd.top = new FormAttachment(0, 25);
    fd.left = new FormAttachment(0, 48);
    secLabel.setLayoutData(fd);

    Label thirdLabel = new Label(container, SWT.WRAP);
    thirdLabel.setText(secondString);

    fd = new FormData();
    fd.top = new FormAttachment(0, 25);
    fd.left = new FormAttachment(secLabel, 3);
    fd.right = new FormAttachment(100, -5);
    thirdLabel.setLayoutData(fd);

    return parent;
  }

}

这是我尝试过的,但问题是德语和英语的斜体和粗体文字都出现在不同的地方,所以对于相同的尺寸它们并不合适。如果我使用不同尺寸,那就好了。

1 个答案:

答案 0 :(得分:5)

要在SWT中显示样式化文本,您可以使用Browser窗口小部件或StyledText窗口小部件。在这两种情况下,您可能需要将默认外观和行为更改为类似标签(即背景颜色,只读)

浏览器小工具

Browser browser = new Browser( parent, SWT.NONE );
browser.setText( "If you restore data the changes will be <b>lost</b>, So <i>recheck</i> once" );

样式文字

StyledText text = new StyledText( parent, SWT.NONE );
text.setText( "If you restore data the changes will be lost, So recheck once" );

通过StyleRange,您可以定义文本部分的格式。样式范围包含startlength,用于指定应用文本的部分,以及TextStyle来控制要应用的样式属性。要让第一个字符显示为粗体,代码将如下所示:

StyleRange styleRange = new StyleRange( 0, 1, null, null, SWT.BOLD );
text.setStyleRanges( new StyleRange[]{ styleRange } );

<强> FORMTEXT

如果您已经依赖org.eclipse.ui.forms,则另一个选项是使用FormText窗口小部件。它支持HTML,如文本中的标记,类似于浏览器小部件。这可能是最像标签的小部件,但拖延了一个额外的依赖。

相关问题