SWT/Jface 如何销毁控件,如何重新生成控件?
看到网上有人提出这样的问题,他的代码是有些问题的。
不在乎问题有多深,在乎解决方法和点滴的积累。
完整的小例子,大家可以跑跑,点点。
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class DynamSample{
Display display;
Shell shell;
Composite c;
Composite c1;
Composite c2;
public DynamSample(){
display = new Display();
shell = new Shell(display);
shell.setText("SWT Sample");
shell.setLayout( new FillLayout(SWT.VERTICAL));
c = new Composite(shell, SWT.NONE);
c.setLayout( new FillLayout() );
createGui1();
createGui2();
shell.open();
while (!shell.isDisposed())
if (!display.readAndDispatch())
display.sleep();
}
private void createGui1(){
c1 = new Composite(c, SWT.NONE);
c1.setLayout(new GridLayout(1, true));
Button b1 = new Button( c1, SWT.NONE);
b1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
b1.setText("Button 1");
b1.addSelectionListener(new SelectionListener(){
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
@Override
public void widgetSelected(SelectionEvent e) {
c1.dispose(); //先销毁了
createGui3(); //在重新加载上???但不成功
//按添加的
c1.layout();
c.layout();
//
}});
}
private void createGui2(){
Composite c2 = new Composite(c, SWT.NONE);
c2.setLayout(new GridLayout( 1, true ));
Button b2 = new Button( c2, SWT.NONE);
b2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
b2.setText("Button 2");
b2.addSelectionListener(new SelectionListener(){
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
@Override
public void widgetSelected(SelectionEvent e) {
// 功能如上
}
});
}
private void createGui3(){
c1 = new Composite(c, SWT.NONE);
c1.setLayout(new GridLayout( 1, true ));
Button b1 = new Button( c1, SWT.NONE);
b1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
b1.setText("Button 2222222");
b1.addSelectionListener(new SelectionListener(){
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
@Override
public void widgetSelected(SelectionEvent e) {
// 功能如上
}
});
}
public static void main(String args[]){
new DynamSample();
}
}