簡體   English   中英

計算Composite的最小大小

[英]Compute the minimum size of a Composite

我需要計算一個Composite的最小或默認大小,它可以顯示所有組件而不會剪切。

我似乎只找到計算Composite首選大小的方法。 這意味着Table或其他滾動復合將具有首選大小,其顯示完整內容而不滾動。 ScrolledComposite將立即進入滾動模式,這不是我想要的。

GridLayout通過將GridData提示視為最小寬度/高度來設法實現此目的,允許抓取任何可用的額外空間。

問題與此有關: SWT - 用於ScrolledComposite內的多行文本字段的computingSize

Control#computeSize(int, int)應該是您要搜索的內容:

Point size = comp.computeSize(SWT.DEFAULT, SWT.DEFAULT);
System.out.println(size.x + " " + size.y);

我設法找到了解決方案。

關鍵是兩件事:

  1. 確保在內容上設置調整大小偵聽器(如果添加了CHILDREN並調用了layout())和ScrolledComposite (如果從子ScrolledComposite外部調整大小)
  2. 確保設置GridData.grabGridData.hint 當你執行computeSize() ,提示將確保復合假定這個大小,而抓取確保它將獲取任何可用的額外空間。

代碼示例如下:

public static void main (String [] args) {
  Display display = new Display ();
  Shell shell = new Shell(display);
  ScrolledComposite sc = new ScrolledComposite(shell, SWT.NONE);
  Composite foo = new Composite(sc, SWT.NONE);
  foo.setLayout(new GridLayout(1, false));
  StyledText text = new StyledText(foo, SWT.NONE);
  text.setText("Ipsum dolor etc... \n etc... \n etc....");
  GridDataFactory.fillDefaults().grab(true, true).hint(40, 40).applyTo(text);

  Listener l = new Listener() {
     public void handleEvent(Event e) {
         Point size = sc.getSize();
         Point cUnrestrainedSize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);
         if(size.y >= cUnrestrainedSize.y && size.x >= cUnrestrainedSize.x) {
           content.setSize(size);
           return;
         }
         // does not fit
         Rectangle hostRect = getBounds();
         int border = getBorderWidth();
         hostRect.width -= 2*border;
         hostRect.width -= getVerticalBar().getSize().x;
         hostRect.height -= 2*border;
         hostRect.height -= getHorizontalBar().getSize().y;
         c.setSize(
           Math.max(cUnrestrainedSize.x, hostRect.width),
           Math.max(cUnrestrainedSize.y, hostRect.height)
         );
     }
  }
  sc.addListener(SWT.Resize, l);
  foo.addListener(SWT.Resize, l);

  shell.open ();
  while (!shell.isDisposed ()) {
    if (!display.readAndDispatch ()) display.sleep ();
  }
  display.dispose ();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM