【问题标题】:How to implememt a dynamic sized shell with a ScrolledComposite in eclipse SWT?如何在 Eclipse SWT 中使用 ScrolledComposite 实现动态大小的外壳?
【发布时间】:2018-04-07 17:42:08
【问题描述】:

我创建了一个 Shell 并向其中添加了一个 ScrolledComposite,其中包含一个 Text 作为其内容。但我希望外壳根据内容大小动态更改大小。我的实现如下

    shell.setLayout(new GridLayout(1,true));
    ScrolledComposite sc = new ScrolledComposite(shell, SWT.V_SCROLL|SWT.H_SCROLL);
    sc.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).hint(200, 200).create());  

    sc.setExpandHorizontal(true);
    sc.setExpandVertical(true);

    Composite top = new Composite(sc,SWT.NONE);
    top.setLayout(GridLayoutFactory.swtDefaults().numColumns(1).create());

    StyledText styledText = new StyledText(top, SWT.NONE);
    styledText.setText(text);

    StyleRange style = new StyleRange();
    style.start = 0;
    style.length = text.indexOf(":"); //$NON-NLS-1$
    style.fontStyle = SWT.BOLD;     
    styledText.setStyleRange(style);    


    sc.setContent(top);
//  shell.setSize(sc.computeSize(SWT.DEFAULT, SWT.DEFAULT));
    sc.setMinSize(top.computeSize(SWT.DEFAULT, SWT.DEFAULT));

    sc.pack(true);
    shell.setVisible(true);

当我取消注释上面代码中的注释行时,shell 正在根据内容调整大小,但在这种情况下无法实现滚动条。

如果内容超出特定限制,我也想获得滚动条。如果内容在限制范围内,我不希望 shell 有多余的空格。

有人可以帮我吗??

【问题讨论】:

  • StyledText 支持滚动本身,它不需要在ScrolledComposite 中。

标签: java eclipse swt rcp scrolledcomposite


【解决方案1】:

StyledText支持滚动本身不需要使用ScrolledComposite

Shell shell = new Shell(display, SWT.SHELL_TRIM);

shell.setLayout(new GridLayout());

StyledText text = new StyledText(shell, SWT.V_SCROLL | SWT.H_SCROLL);

text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

text.setText(....);

shell.layout();

Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);

shell.setSize(Math.min(size.x, 100), Math.min(size.y, 100));

shell.open();

不要使用shell.pack(),而是调用shell.layout,然后调用shell.computeSize 来查看未滚动的大小。如果太大,请调整大小并致电shell.setSize

【讨论】:

  • 如何使用 StyledText 仅在数据超过一定限制时显示滚动条?例如,如果文本超过 100 行,则应出现滚动条。这可能吗?
  • 这段代码在 macOS 上为我做这件事。可能它在其他平台上不是那么聪明(我无法测试)。
猜你喜欢
  • 2020-03-05
  • 2014-02-21
  • 2018-05-11
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2012-10-01
  • 2020-04-26
  • 1970-01-01
相关资源
最近更新 更多