【问题标题】:How can we auto resize the size of components in SWT?我们如何在 SWT 中自动调整组件的大小?
【发布时间】:2012-10-07 09:09:47
【问题描述】:

在我的 SWT 应用程序中,我在 SWT shell 中有某些组件。

现在我如何根据显示窗口的大小自动调整这些组件的大小。

Display display = new Display();

Shell shell = new Shell(display);
Group outerGroup,lowerGroup;
Text text;

public test1() {
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns=1;
    shell.setLayout(gridLayout);

    outerGroup = new Group(shell, SWT.NONE);

    GridData data = new GridData(1000,400);
    data.verticalSpan = 2;
    outerGroup.setLayoutData(data);    

    gridLayout = new GridLayout();

    gridLayout.numColumns=2;
    gridLayout.makeColumnsEqualWidth=true;
    outerGroup.setLayout(gridLayout);

    ...
}

即当我减小窗口的大小时,它里面的组件应该按照那个显示。

【问题讨论】:

  • 您可以监听SWT.Resize事件并在组件上调用layout()

标签: java layout resize swt


【解决方案1】:

这听起来很可疑,就像您没有使用布局一样。

布局的整个概念使担心调整大小变得不必要。布局将处理其所有组件的大小。

我建议阅读Eclipse article about layouts

您的代码很容易被更正。不要设置单个组件的大小,布局将决定它们的大小。如果您希望窗口具有预定义的大小,请设置外壳的大小:

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(1, false));

    Group outerGroup = new Group(shell, SWT.NONE);

    // Tell the group to stretch in all directions
    outerGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    outerGroup.setLayout(new GridLayout(2, true));
    outerGroup.setText("Group");

    Button left = new Button(outerGroup, SWT.PUSH);
    left.setText("Left");

    // Tell the button to stretch in all directions
    left.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    Button right = new Button(outerGroup, SWT.PUSH);
    right.setText("Right");

    // Tell the button to stretch in all directions
    right.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    shell.setSize(1000,400);
    shell.open();

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

调整大小之前:

调整大小后:

【讨论】:

  • 如果我希望对话框/shell 的初始大小是其内容的大小怎么办?我的意思是,按钮的最小尺寸也取决于它们的内容,那么我怎样才能将它们的容器设置为它们的尺寸呢?这在各种语言翻译的情况下很有用(例如,德语可能比中文/日语长)。
  • @androiddeveloper 在他们的父级甚至Shell 上调用pack()
  • @Baz 似乎有效,但不适用于“FormLayout”。也许是因为我(出于懒惰)使用了绝对职位。此外,由于某种原因,当我尝试创建一个位于主 Shell 内部的新 Shell 并将其设为中心时(如这里:java2s.com/Code/Java/SWT-JFace-Eclipse/DialogShell.htm),它似乎没有正确定位它。你知道为什么吗?
  • @androiddeveloper 这不适用于绝对位置。这就是为什么你不应该使用它们。如果没有详细信息,无法帮助您解决其他问题。也许值得发布一个新问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2016-09-23
  • 1970-01-01
  • 2015-07-21
  • 2017-04-08
相关资源
最近更新 更多