【问题标题】:How to set the max height of ScrolledComposite in SWT如何在 SWT 中设置 ScrolledComposite 的最大高度
【发布时间】:2017-07-04 10:57:09
【问题描述】:

我有一个带有按钮的ScrolledComposite,它在“下一行”下方创建一个新按钮。每次我用pack()调整我的合成高度。

但现在我想设置最大高度,这样,从某个尺寸开始,窗口的高度保持不变,我得到一个垂直滚动条。

【问题讨论】:

    标签: java swt scrolledcomposite


    【解决方案1】:

    调用pack() 将始终调整控件的大小,以便它可以显示其全部内容。相反,滚动组合的大小应由其父级的布局管理。这就是滚动组合的全部目的:显示包含的控件并在需要时提供滚动条。

    使用setMinSize() 控制何时显示滚动条。下面的示例具有一个带有单个按钮的滚动组合。按下按钮将添加另一个按钮。请注意,添加按钮后,最小尺寸会在updateMinSize() 中重新计算。

    public class DynamicScrolledComposite {
    
      public static void main( String[] args ) {
        Display display = new Display();
        Shell shell = new Shell( display );
        shell.setLayout( new FillLayout() );
        ScrolledComposite scrolledComposite = new ScrolledComposite( shell, SWT.H_SCROLL | SWT.V_SCROLL );
        scrolledComposite.setExpandVertical( true );
        scrolledComposite.setExpandHorizontal( true );
        scrolledComposite.addListener( SWT.Resize, event -> updateMinSize( scrolledComposite ) );
        Composite composite = new Composite( scrolledComposite, SWT.NONE );
        composite.setLayout( new GridLayout( 1, false ) );
        createButton( composite );
        scrolledComposite.setContent( composite );
        shell.setSize( 600, 300 );
        shell.open();
        while( !shell.isDisposed() ) {
          if( !display.readAndDispatch() )
            display.sleep();
        }
        display.dispose();
      }
    
      private static void updateMinSize( ScrolledComposite scrolledComposite ) {
        Rectangle clientArea = scrolledComposite.getClientArea();
        clientArea.width -= scrolledComposite.getVerticalBar().getSize().x;
        Point minSize = scrolledComposite.getContent().computeSize( clientArea.width, SWT.DEFAULT );
        scrolledComposite.setMinSize( minSize );
      }
    
      private static void createButton( Composite parent ) {
        Button button = new Button( parent, SWT.PUSH );
        button.setText( "Add another button" );
        button.addListener( SWT.Selection, new Listener() {
          @Override
          public void handleEvent( Event event ) {
            createButton( parent );
            ScrolledComposite scrolledComposite = ( ScrolledComposite )button.getParent().getParent();
            button.getParent().requestLayout();
            updateMinSize( scrolledComposite );
          }
        } );
      }
    }
    

    要详细了解ScrolledComposite 的不同内容管理策略,请参阅此处:http://www.codeaffine.com/2016/03/01/swt-scrolledcomposite/

    【讨论】:

    • 非常感谢,效果很好。但是现在我有一个问题,如果我减小窗口的宽度,我会看到一个垂直条并单击一个按钮,那么这个条就会消失。但这是另一个问题。再次感谢您。
    猜你喜欢
    • 2014-10-07
    • 2014-06-07
    • 2020-02-10
    • 2023-04-08
    • 2017-07-30
    • 2011-04-04
    • 2017-05-22
    • 1970-01-01
    • 2016-10-26
    相关资源
    最近更新 更多