我新建了一个Application Window,里面有个参数String str="wang",再新建了一个Dialog类,当点击Application Window的某个按钮时,如何将str传递给这个Dialog,说说思路就行。
Dialog的代码如下:
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;public class GetString extends Dialog { private Text text;
protected Object result;
protected Shell shell; /**
* Create the dialog
* @param parent
* @param style
*/
public GetString(Shell parent, int style) {
super(parent, style);
} /**
* Create the dialog
* @param parent
*/
public GetString(Shell parent) {
this(parent, SWT.NONE);
} /**
* Open the dialog
* @return the result
*/
public Object open() {
createContents();
shell.open();
shell.layout();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
return result;
} /**
* Create contents of the dialog
*/
protected void createContents() {
shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
shell.setSize(500, 375);
shell.setText("SWT Dialog"); text = new Text(shell, SWT.BORDER);
text.setBounds(135, 138, 151, 33);
//
}}
Dialog的代码如下:
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;public class GetString extends Dialog { private Text text;
protected Object result;
protected Shell shell; /**
* Create the dialog
* @param parent
* @param style
*/
public GetString(Shell parent, int style) {
super(parent, style);
} /**
* Create the dialog
* @param parent
*/
public GetString(Shell parent) {
this(parent, SWT.NONE);
} /**
* Open the dialog
* @return the result
*/
public Object open() {
createContents();
shell.open();
shell.layout();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
return result;
} /**
* Create contents of the dialog
*/
protected void createContents() {
shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
shell.setSize(500, 375);
shell.setText("SWT Dialog"); text = new Text(shell, SWT.BORDER);
text.setBounds(135, 138, 151, 33);
//
}}
既然你已经新建了一个Dialog类,那么,这个类里面提供接受一个字符串(或者包括该参数的若干个参数)的函数不就可以了?你想要传递什么类型,就提供相应的借口。使用这个对话框的时候把相应的信息设置进去。在显示前调用。
呵呵,不知道你是不是这个意思?
比如,构造函数传进去,将GetString Dialog的构造函数改变一下(appValue就是你要从主窗体传过去的参数值):
在主窗体中触发Dialog显示时,在初始化的时候传进去。 private String appValue;
public GetString(Shell parent, int style,String appValue) {
super(parent, style);
this.appValue = appValue;
}或者,增加getter、setter方法,无论在主窗体中还是在Dialog中都可以使用。
你建Dialog的时候,在构造函数里面加参数就行了。很简单。
举个例子:MainFrame中打开SubDialog,并要传递参数Str的话
新建一个SubDialog,构造函数为:SubDialog(MainFrame mainFrame,String str )
你在MainFrame中new SubDialog(MainFrame mainFrame,String str).setVisible(True)即可