有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在swt中生成子复合填充父

这是我的密码:

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

    Composite childComposite = new Composite(shell, SWT.BORDER);
    childComposite.setLayout(new GridLayout(2, false));
    Text text1 = new Text(childComposite, SWT.NONE);
    Text text2 = new Text(childComposite, SWT.NONE );

    Label label = new Label(shell, SWT.NONE);
    label.setText("Very loooooooooooooooooooooooong text");

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

这将产生如下结果:

enter image description here

我的问题是如何使我的子组合水平填充父组合(至少与下面的标签宽度相同)。 我试着用这样的方法:

Composite childComposite = new Composite(shell, SWT.BORDER | SWT.FILL);

。。。但这并没有改变任何事情

此外,当子控件的宽度与父控件的宽度相同时,我希望文本小部件也填充它们所在的组合,但宽度不同-例如,第一个是20%,第二个是80%。 我应该检查哪些可能性来实现这一点


共 (1) 个答案

  1. # 1 楼答案

    使用GridLayout时,可以使用GridData参数来控制setLayoutData方法,以指定网格的填充方式

    你想要的是:

      shell.setLayout(new GridLayout(1, false));
    
      Composite childComposite = new Composite(shell, SWT.BORDER);
    
      // Composite fills the grid row
      childComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    
      // Use 5 equal sized columns
      childComposite.setLayout(new GridLayout(5, true));
    
      // First text fills the first column
      Text text1 = new Text(childComposite, SWT.NONE);
      text1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
    
      // Second text fills the next 4 columns
      Text text2 = new Text(childComposite, SWT.NONE);
      text2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1));
    
      Label label = new Label(shell, SWT.NONE);
      label.setText("Very loooooooooooooooooooooooong text");