满意答案
mikeliuqing
2013.05.13
采纳率:45% 等级:13
已帮助:9168人
先说明一下:没用过swt,所以不知道还有没有更好的获取被监听对象的方法。按照自己的想法做了一下,获取成功了。 在你的程序上小改了一下,具体看注释吧,我都写上面了。==================
public class MainClass {
public static void main(String[] args){
Login login = new Login();
}
}
=============import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;public class Login { Display display;
Shell shell;
private Text username;//抽出用户名输入框属性作为全局变量
public Login() {
// TODO Auto-generated constructor stub
display = new Display();
shell = new Shell(display);
shell.setSize(250, 250); GridLayout gridLayout = new GridLayout();
// 创建有三栏宽的grid,超过3栏的控件自动转到第二行第一栏
gridLayout.numColumns = 2;
shell.setLayout(gridLayout); Label label = new Label(shell, SWT.CENTER);
label.setText("Name:");
username = new Text(shell, SWT.BORDER); Label labe2 = new Label(shell, SWT.CENTER);
labe2.setText("Password:");
Text password = new Text(shell, SWT.BORDER);
password.setEchoChar('*'); Button button = new Button(shell, SWT.CENTER);
button.setText("登录"); Button button2 = new Button(shell, SWT.CENTER);
button2.setText("取消"); button.addSelectionListener(new LoginListener(this));//传入 登陆框对象,便于监听类获取本类中的属性
// button2.addSelectionListener(new Exit()); shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
} public Text getUsername() {
return username;
} /**
* 添加get 方法。一:安全; 二:便于其他类获取值
* @param username
*/
public void setUsername(Text username) {
this.username = username;
}}
===============import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;public class LoginListener implements SelectionListener {
private Login login;//添加被监听对象的属性。
//自定义一个构造函数,便于获取属性。
public LoginListener (Login login){
this.login = login;
}
public void widgetDefaultSelected(SelectionEvent arg0) {
// TODO Auto-generated method stub } public void widgetSelected(SelectionEvent se) {
// TODO Auto-generated method stub
Button b = (Button)se.getSource();
if("登录".equals(b.getText())){
String username = login.getUsername().getText();
System.out.println(username);
}
}}
20分享举报