单击swt中的按钮时如何创建文本框?

时间:2018-10-11 06:02:04

标签: swt eclipse-rcp rcp e4

我在swt中创建了2个复合。在第一个组合内创建了1个按钮。当我单击按钮时,我想创建一个文本框。但是我无法执行该功能。

1 个答案:

答案 0 :(得分:1)

假设您正在为代码使用布局,则只需创建Text控件,然后重做布局即可。

例如,使用GridLayout

shell.setLayout(new GridLayout());

final Composite buttonComposite = new Composite(shell, SWT.NONE);
buttonComposite.setLayout(new GridLayout());

final Button button = new Button(buttonComposite, SWT.PUSH);
button.setText("Create Text");

final Composite textComposite = new Composite(shell, SWT.NONE);
textComposite.setLayout(new GridLayout());

button.addSelectionListener(new SelectionAdapter()
  {
    @Override
    public void widgetSelected(final SelectionEvent e)
    {
      final Text newText = new Text(textComposite, SWT.SINGLE | SWT.BORDER);
      newText.setText("New text control");

      newText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

      // Update the layout

      shell.layout(true);
    }
  });

或者,您可以在开始时创建Text控件,但使其不可见并将其从布局中排除:

shell.setLayout(new GridLayout());

final Composite buttonComposite = new Composite(shell, SWT.NONE);
buttonComposite.setLayout(new GridLayout());

final Button button = new Button(buttonComposite, SWT.PUSH);
button.setText("Create Text");

final Composite textComposite = new Composite(shell, SWT.NONE);
textComposite.setLayout(new GridLayout());

final Text newText = new Text(textComposite, SWT.SINGLE | SWT.BORDER);
newText.setText("New text control");

// Not visible

newText.setVisible(false);

// Exclude from layout

final GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false);
data.exclude = true;
newText.setLayoutData(data);

button.addSelectionListener(new SelectionAdapter()
  {
    @Override
    public void widgetSelected(final SelectionEvent e)
    {
      // Include in layout

      final GridData data = (GridData)newText.getLayoutData();
      data.exclude = false;

      // Make visible

      newText.setVisible(true);

      // Redo layout

      shell.layout(true);
    }
  });