【问题标题】:How to dispose a widget and create another widget in place of that in SWT?如何在 SWT 中处理一个小部件并创建另一个小部件来代替它?
【发布时间】:2017-06-16 11:23:23
【问题描述】:

我有一个组合,我在启动视图时创建了五个文本框。有一个点击按钮,我想用组合框替换第四个文本框。问题是我无法从头开始重新加载页面,因为我想显示文本框的当前值。

这是一个sn-p。

public class DisposeDemo {
  private static void addControls(Shell shell) {
    shell.setLayout(new GridLayout());
    Text textOne=new Text(shell, SWT.BORDER);
    Text textTwo=new Text(shell, SWT.BORDER);
    Text textThree=new Text(shell, SWT.BORDER);
    Text textFour=new Text(shell, SWT.BORDER);
    Text textFive=new Text(shell, SWT.BORDER);

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Replace text with Combo");

    button.addSelectionListener(new SelectionAdapter() {
      @Override public void widgetSelected(SelectionEvent event) {

         //What code should go here to Replace the textFour with a combo

      }
    });
    shell.pack();
  }

  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    addControls(shell);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
}

【问题讨论】:

    标签: java layout swt


    【解决方案1】:

    与其尝试替换控件(这很棘手),不如一开始就创建所有控件,但使其中一个不可见并将其从布局中排除。然后,您可以稍后切换可见性。

    创建使用时:

    Text textFour = new Text(shell, SWT.BORDER);
    GridData data = new GridData(SWT.LEFT, SWT.CENTER, false, false);
    textFour.setLayoutData(textFour);
    
    Combo comboFour = new Combo(shell, ... style ...);
    comboFour.setVisible(false);   // Not visible
    data = new GridData(SWT.LEFT, SWT.CENTER, false, false);
    data.exclude = true;   // Exclude from layout
    comboFour.setLayoutData(data);
    

    切换以使组合可见:

    textFour.setVisible(false);
    GridData data = (GridData)textFour.getLayoutData();
    data.exclude = true;
    
    comboFour.setVisible(true);
    data = (GridData)comboFour.getLayoutData();
    data.exclude = false;
    
    shell.layout(true);   // Tell shell to redo the layout
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 2021-09-28
    • 1970-01-01
    • 2020-03-08
    • 2012-08-05
    • 2011-01-18
    相关资源
    最近更新 更多