在swt中点击按钮时如何创建一个文本框?

How to create a text box when click on button in swt?

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

假设您正在为您的代码使用布局,您只需创建文本控件,然后重做布局。

例如,使用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);
    }
  });

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

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);
    }
  });